Archive

Archive for June, 2015

Efficient Image Resizing With ImageMagick

June 25th, 2015 No comments
HTTP archive pie chart of average bytes per page by content type

Responsive1images2 have been keeping us on our toes for quite some time, and now that they are getting traction in browsers, they come with a scary problem: the need to efficiently resize all our image assets. The way responsive images work is that an appropriately sized image is sent to each user — small versions for users on small screens, big versions for users on big screens.

It’s fantastic for web performance, but we have to face the grim reality that serving different sizes of images to different users means that we first need to create all of those different files, and that can be a huge pain3.

Many tools out there automate image resizing, but too often they create large files that cancel out the performance benefits that responsive images are supposed to deliver. In this article, we’ll see how we can use ImageMagick134 — an open-source command-line graphics editor — to quickly resize your images, while maintaining great visual quality and really tiny file sizes.

Big Images == Big Problem

The average web page is about 2 MB5 in size, and about two thirds of that weight is from images. At the same time, millions of people are accessing the Internet on 3G-or-worse connections that make a 2 MB website a horror show to use. Even on a fast connection, a 2 MB website can wreak havoc on your users’ data plans and cost them real money6. Improving web performance and giving a better experience to our users is our job as developers and designers.

7
The average web page is 2,099 KB, 1,310 KB of which comes from images. (Image: HTTP Archive8) (View large version9)

Responsive images10 to the rescue! Right? Well, yes, but first we have to generate our responsive image assets, and we have to make sure those assets look good and have a small enough footprint to improve the website’s performance.

For a very small website, saving a few different sizes of each image directly in our image editor is trivial — Photoshop even provides a handy “Save for Web” option that keeps file sizes low. But what about a large website with a lot of images? An online store, for example, might have hundreds or thousands of image assets, and having to create different sizes of each of these is an enormous task.

ImageMagick

This is where automated image resizing comes in handy. A bunch of tools out there do this, including GD11 and GraphicsMagick12, but ImageMagick134 strikes a good balance between power and availability in hosting environments. ImageMagick has been around for almost 25 years and is a full-fledged command-line image editor. It is widely supported by content management systems (CMS) such as WordPress7014 and Drupal7515, integrated with task runners such as Grunt8216, and used on its own to automate image editing — including resizing.

It’s also available on desktop systems (Mac, Windows and Linux). If you use Homebrew17 on a Mac, you can install it like this:

brew install imagemagick

Otherwise, look for it in your favorite package manager, or download it directly from the ImageMagick website18.

ImageMagick provides a fast, simple way to automate image resizing. Unfortunately, with the default settings, the resized files it outputs are often really big — sometimes bigger than the inputted image, even though the output has fewer pixels. These big files completely negate the performance gains you’d expect to get from responsive images and, in fact, can make things worse for your users than if you’d simply loaded the huge unshrunk assets.

Below, I’ll describe why this problem exists and show you how to change ImageMagick’s default settings to solve this problem and get small, great-looking images.

How Image Resizing Works

The best way to solve the problem is to understand why it’s happening, and that means understanding the basics of how image resizing works.

By definition, when a computer resizes an image, the number of pixels in that image will change. If the image is being enlarged, the output will have more pixels than the input; if the image is being shrunk, the output will have fewer pixels than the input. The challenge is in figuring out the best way to store the original image’s content in this different number of pixels. In other words, we need to figure out the best way to add or remove pixels without changing what the image looks like.

Although not as common a use case, image upsampling (i.e. making images larger) can be a little easier to visualize, so let’s start with that. Consider an image of a blue 4 × 4 pixel square that we want to double in size to 8 × 8 pixels. What we’re doing is taking the same image and applying it to a new pixel grid; this is called resampling and is usually what we mean when we talk about resizing images. To resample our 4 × 4 blue square to 8 × 8 pixels, we need to add 48 extra pixels somewhere. Those pixels will need some color value, and the process of determining that color value is called interpolation. When you’re resampling, the algorithm for determining how the interpolation works is called a resampling filter.

19
How do we resample a 4 × 4 pixel square to an 8 × 8 pixel grid? (View large version20)

We could use all sorts of resampling filters and interpolation methods to figure out those 48 extra pixels. The absolute simplest thing we could do is to add four more rows and four more columns of pixels in some arbitrary color — say, red. This is called background interpolation, because the empty pixels are simply exposing a background color (red). This is what you’re doing in Photoshop when you resize using “Image” ? “Canvas Size,” instead of “Image” ? “Image Size.”

This, of course, is a terrible outcome when we want to resize an image: we don’t perceive the new outputted image to really look like the original inputted image at all; the original square is blue, the new one is blue and red. Background interpolation is only possible when adding pixels (i.e. when making the image bigger or when upsampling), and even then it is essentially useless for resizing, except as a means to show where the new pixels are.

A pink and blue square21
Background interpolation. (View large version22)

Another very simple interpolation method is to make our new pixels the same color as their neighboring pixels; this is called nearest-neighbor interpolation. This produces a much better result than background interpolation, especially for a simple square like this.

A blue square23
Nearest-neighbor interpolation: upsampling a square. (View large version24)

Downsampling (i.e. making the image smaller) with nearest-neighbor interpolation is not as intuitive as upsampling, but it helps to remember that the math involved is OK with fractional pixels. First, the new pixel grid gets applied to the orignal image. Because there are fewer pixels to store the image information, some of the pixels in this new grid will contain multiple colors; in the example below, some pixels contain both blue and white.

Outputting the image in this way to the physical pixels in the real world isn’t possible, though — each pixel can be only one color. The final color of each pixel in the new grid is determined by the color at its center point. In other words, that center point is sampled to determine the final color, which is why nearest-neighbor interpolation is sometimes called point sampling.

Four images: a circle; an 8×8 pixel grid; the grid overlayed on top of the circle with the center marked; and the resized circle, which is blocky and not very circular25
Nearest-neighbor interpolation: downsampling a circle. (View large version26)

For anything more complicated than a line or square, nearest-neighbor interpolation produces very jagged, blocky images. It’s fast and creates small files but doesn’t look very good.

Most resampling filters use some sort of variation on nearest-neighbor interpolation — they sample multiple points to determine the color of a pixel and use math to try to come up with a smart compromise for those values. Bilinear interpolation, for example, creates a weighted average of colors. It produces much nicer results than nearest-neighbor interpolation.

Two circles27
Bilinear interpolation. (View large version28)

One way that resampling — and the specific resampling filter used — can affect file size is by affecting the colors in the image. Bilinear interpolation gives the circle smooth edges, but that means giving the image more colors. The original blue circle has two colors, blue and white. The resized circle has more — some pixels are a pale bluey-white. All else being equal, more colors in an image will make the file size bigger. This is one reason why resizing an image to have fewer pixels sometimes gives it more bytes.

What All This Means for Us

In order to make our outputted images smaller, we’ll want to look at ways to reduce the number of colors without sacrificing quality. Choosing an appropriate resampling filter has one of the biggest effects, but other settings can affect the number of colors in the output as well. I’ll also discuss settings that control file compression and quality and that eliminate extraneous data.

Optimal Settings For ImageMagick

ImageMagick Basics

ImageMagick has a ton of options and functions29, and finding a good combination of these can be tricky.

Two main ImageMagick settings are of interest to us, convert and mogrify. Both of these perform similar operations, but mogrify is intended to be used with multiple files at once, while convert handles only one image at a time.

A simple ImageMagick operation might look like this:

convert input.jpg -resize 300 output.jpg

This says that we want ImageMagick’s convert function to take input.jpg and resize it to 300 pixels wide, and then save that to output.jpg. The -resize 300 part is an example of one of ImageMagick’s many built-in functions. Each function uses the same format: -functionName option.

Using mogrify is similar, but with the syntax reordered a bit:

mogrify -path output/ -resize 300 *.jpg

This says that we want ImageMagick’s mogrify function to take all JPEG files in the current directory (*.jpg), resize them to 300 pixels wide and then save them in the output directory.

Functions can be combined for more complex results:

convert input.jpg -resize 300 -quality 75 output.jpg

As before, this resizes input.jpg to 300 pixels wide, but this time it also sets the JPEG quality to 75 before saving it to output.jpg.

I’ve performed hundreds of tests30 to see which combinations of functions and options produce the smallest results at an acceptable quality.

Testing and Results

I wanted to keep the file size as low as possible but keep the quality high — indistinguishable from Photoshop’s “Save for Web.” To do this, I used both a subjective quality measure — my own opinion on whether the output looks good — and an objective quality measure — structural dissimilarity31 (DSSIM). DSSIM compares two images — in this case, my test image and a control generated by Photoshop’s “Save for Web” — and generates a score. The lower the score, the more the images resemble each other; a score of zero means they are identical. To make sure test images look the same as Photoshop’s output, I wanted a mean DSSIM score of 0.0075 or lower. In research released last year32, RadWare33 found that image pairs with a DSSIM score of 0.015 were indistinguishable to their test users.

To make sure the results weren’t biased by outliers, I tested on 40 images that are a mixture of JPEGs and PNGs; photos, drawings and line art; color and monochrome; transparent and opaque. I also tested at three output sizes (300, 600 and 1200 pixels wide) from a variety of input sizes. Finally, I tested both with and without image optimization.

From my tests, running ImageMagick with the following settings produced the smallest results, while generally being visually indistinguishable from Photoshop’s output:

mogrify -path OUTPUT_PATH -filter Triangle -define filter:support=2 -thumbnail OUTPUT_WIDTH -unsharp 0.25x0.25+8+0.065 -dither None -posterize 136 -quality 82 -define jpeg:fancy-upsampling=off -define png:compression-filter=5 -define png:compression-level=9 -define png:compression-strategy=1 -define png:exclude-chunk=all -interlace none -colorspace sRGB -strip INPUT_PATH

That’s a lot to take in, so let’s go through each bit and see what it means.

Mogrify vs. Convert

As mentioned, ImageMagick provides two similar tools for manipulating images: convert is the basic image editor and works on one image at a time; mogrify is mostly used for batch image manipulation. In an ideal world, these two tools would produce identical results; unfortunately, that’s not the case — convert has a bug34 that makes it ignore one of the settings I recommend using (the -define jpeg:fancy-upsampling=off setting, discussed below), so using mogrify is better.

Resampling

Choosing a resampling filter in ImageMagick is surprisingly complicated. There are three ways you can do this:

  • with the resizing function you choose,
  • with the -filter setting,
  • or with the -interpolate setting.
Example output from twelve different resizing functions35
One of these things just doesn’t belong here, but the rest look pretty much the same, which is why I used an objective quality measure. (Image: Richard Fisher6148454236) (View large version37)

The most obvious resizing function to use is -resize, but it creates files that are too large. I looked at 11 different functions and found that -thumbnail does the best job of optimizing quality and file size. In most cases, the -thumbnail function uses a three-step process to resize images:

  1. It resizes the image to five times the output size using the -sample function, which has its own built-in resampling filter that’s similar to the nearest-neighbor approach discussed above.
  2. It resizes the image to its final output size using the basic -resize filter.
  3. It strips meta data from the image.

This means that if we were resizing an image to be 500 pixels wide, -thumbnail would first resize it to 2,500 pixels wide using -sample; the result might be blocky and pixelated, as we saw in the examples above, but the operation would be fast and would produce a result with a small file size. Then, ImageMagick would resize this image from 2,500 pixels wide to 500 pixels wide using -resize. This smooths out the blockiness, but the file size stays pretty low. Finally, ImageMagick would remove meta data to get an even smaller file.

The second way to choose a resampling filter in ImageMagick is with the -filter setting. Some resizing functions (such as -sample) have a built-in resampling function that’s always used, but others (such as -resize) have defaults that can be overridden with -filter. The -filter setting gets used in -thumbnail‘s second step, because that step uses -resize.

I tested 31 different settings for -filter and got the best results with Triangle. The Triangle resampling filter is also known as bilinear interpolation, which I discussed above. It determines pixel color by looking at a support area of neighboring pixels and produces a weighted average of their colors. I found it best to specify this support area at two pixels using the -define filter:support=2 setting.

The third way to choose a resampling filter, the -interpolate setting, is ignored by -thumbnail, so it’s not needed here.

In addition to the settings above, by default ImageMagick also uses something called JPEG fancy upsampling38, an algorithm that tries to produce better-looking JPEGs. I’ve found that it produces larger files and that the quality difference is negligible, so I recommend turning it off with -define jpeg:fancy-upsampling=off.

Sharpening

Images pretty often get a little blurry when resized, so programs such as Photoshop will often apply some sharpening afterwards to make the images a little crisper. I recommend using an unsharp filter — which, despite its name, actually does sharpen the image — with the setting -unsharp 0.25x0.25+8+0.065.

Unsharp filters work by first applying a Gaussian blur39 to the image. The first two values for the unsharp filter are the radius and sigma, respectively — in this case, both have a value of 0.25 pixels. These values are often the same and, combined, tell ImageMagick how much to blur the image. After the blur is applied, the filter compares the blurred version to the original, and in any areas where their brightness differs by more than a given threshold (the last value, 0.065), a certain amount of sharpening is applied (the third value, 8). The exact meanings of the threshold and numerical amounts aren’t very important; just remember that a higher threshold value means that sharpening will be applied less often, and a higher numerical amount means that the sharpening will be more intense wherever it is applied.

Color Reduction

I mentioned that one of the biggest reasons why resized images get bloated is because of all the extra colors in them. So, try to reduce the number of colors — but not so much that the quality suffers.

One way to reduce colors is with posterization, a process in which gradients are reduced to bands of solid color. Posterization reduces colors to a certain number of color levels — that is, the number of colors available in each of the red, green and blue color channels that images use. The total number of colors in the final image will be a combination of the colors in these three channels.

Posterization can drastically reduce file size, but can also drastically change how an image looks. With only a few color levels, it creates an effect like what you might see in 1970s rock posters40, with a few discrete bands of color. With many color levels — for example, 136, as I’m suggesting — you get a smaller file without losing much image quality.

Close up of an owl with reduced colors41
Original image. (Image: Richard Fisher6148454236) (View large version43)
Close up of an owl with reduced colors44
Posterization reduces the colors in the image. (Image: Richard Fisher6148454236) (View large version46)

Dithering is a process that is intended to mitigate color banding by adding noise into the color bands to create the illusion that the image has more colors. In theory, dithering seems like a good idea when you posterize; it helps the viewer perceive the result as looking more like the original.

Two images of an old woman, the second full of image rendering artifacts47
Dithering. (Image: Richard Fisher6148454236) (View large version49)

Unfortunately, ImageMagick has a bug that ruins images with transparency when dithering is used like this. So, it’s best to turn dithering off with -dither None. Luckily, even without dithering, the posterized images still look good.

Two images of an old woman, the second full of image rendering artifacts50
ImageMagick dithering bug. (Image: Nemo51) (View large version5552)

Color Space

While not strictly a matter of color reduction, setting an image’s color space is a related concept. The color space defines what colors are available for an image. The image below shows that the ProPhoto RGB color space contains more colors than the Adobe RGB color space, which in turn contains more colors than the sRGB color space. All of these contain fewer colors than are visible to the human eye.

Map that compares how much of the color spectrum is covered by different color spaces; sRGB covers the least53
Color spaces. (Image: Cpesacreta54) (View large version5552)

sRGB was created to be the one true king of color spaces on the Internet. It has been endorsed by the W3C and other standards bodies; it is the required color space in the CSS Color Module Level 356 and the SVG specification57 and is the assumed color space of the WebP58 specification; and it is explicitly referenced in the PNG specification59. It’s also the default color space in Photoshop. In short, sRGB is the color space of choice for the web platform, and, assuming you want your images to render predictably, using it is probably a good idea.

Quality and Compression

With lossy image formats such as JPEG, quality and compression go hand in hand: the higher the compression, the lower the quality and the lower the file size. We could drastically reduce file size by setting a high JPEG compression factor, but this would also drastically reduce quality. A balance is needed.

When I was doing my tests, the control images I created with Photoshop had a JPEG quality setting of high, or 60. I’ve found that this setting works well for me and strikes the right balance between quality and file size. However, in my ImageMagick settings, I’m recommending -quality 82. Why?

It turns out that JPEG quality scales are not defined in a specification or standard, and they are not uniform across encoders. A quality of 60 in Photoshop might be the same as a quality of 40 in one program, quality B+ in another and quality fantastico in a third. In my tests, I found that Photoshop’s 60 is closest to -quality 82 in ImageMagick.

For non-lossy image formats, such as PNG, quality and compression are not related at all. High compression doesn’t change how an image looks at all and only comes at the expense of processing load (in terms of CPU usage, memory usage and processing time). Assuming that our computers can handle this load, there’s no reason not to max out PNG compression.

PNG compression in ImageMagick can be configured with three settings, -define png:compression-filter, -define png:compression-level and -define png:compression-strategy. Compression filtering60 is a pre-compression step that reorganizes the image’s data so that the actual compression is more efficient; I got the best results using adaptive filtering (-define png:compression-filter=5). Compression level is the amount of compression that gets applied; I recommend maxing this out to 9 (-define png:compression-level=9). Finally, the compression strategy setting determines the actual algorithm that’s used to compress the files; I got the best result with the default compression strategy (-define png:compression-strategy=1).

Meta Data

In addition to the actual image data, image files can contain meta data: information about the image, such as when it was created and the device that created it. This extra information could take up space without providing any benefit to our users and should usually be removed. Above, when describing the -thumbnail function that handles the actual resizing of the image, I mentioned that its third step involves stripping meta data. Even though that’s true, -thumbnail doesn’t remove all of the meta data, and there are gains to be had by using -strip and -define png:exclude-chunk=all as well. Neither of these should affect quality at all.

Progressive Rendering

JPEGs and PNGs can be saved to use either progressive or sequential rendering. Sequential rendering is usually the default: The image will load pixels row by row from top to bottom. Progressive rendering means the image is delivered and rendered in stages.

For JPEGs, progressive rendering can happen in any number of stages, as determined when the file is saved. The first stage will be a very low-resolution version of the full image; at each subsequent stage, a higher-resolution version is delivered until, in the last stage, the full-quality version is rendered.

An owl, rendering at progressively higher quality
Progressive JPEG simulation. (Image: Richard Fisher6148454236)

PNGs use a type of progressive rendering called Adam7 interlacing62, in which the pixels of the image are delivered in seven stages based on an 8 × 8 pixel grid.

Pixels being rendered in seven passes
Adam7 interlacing. (Image: CountingPine63)

Both types of progressive rendering can be controlled in ImageMagick using the -interlace setting. But should progressive rendering be turned on or not?

For both JPEGs and PNGs, progressive rendering increases the file size, but for a long time conventional wisdom held that it was worth turning on64 because it delivered a better experience to the user. The idea is that even if the full, perfect image doesn’t load quite as quickly, users would be able to see something earlier, and that something is probably better than nothing.

Last year, though, Radware65 released research on progressive JPEGs66 that shows users actually tend to prefer sequential image rendering. This is just one study (and one that hasn’t gone through a formal peer review process), but the results are interesting. Radware’s results, combined with the fact that sequential images have smaller file sizes, lead me to recommend the -interlace none setting in ImageMagick.

Image Optimization

I mentioned above that I ran tests both with and without image optimization. All of the settings I’ve described so far are what I’d recommend if you’re not optimizing your images. If you can optimize them, though, my recommendations would change slightly: I found that slightly different -unsharp settings work better (-unsharp 0.25x0.08+8.3+0.045 versus -unsharp 0.25x0.25+8+0.065 without optimization) and that there’s no need to use -strip.

mogrify -path OUTPUT_PATH -filter Triangle -define filter:support=2 -thumbnail OUTPUT_WIDTH -unsharp 0.25x0.08+8.3+0.045 -dither None -posterize 136 -quality 82 -define jpeg:fancy-upsampling=off -define png:compression-filter=5 -define png:compression-level=9 -define png:compression-strategy=1 -define png:exclude-chunk=all -interlace none -colorspace sRGB INPUT_PATH

A lot of different image optimizers are out there. I tested image_optim67, picopt68 and ImageOptim69, all of which run images through a battery of different optimization steps. I tested these tools both individually and in combination, and I found that the best results come from running files through all three, in the order listed above. That said, there are diminishing returns: After the first round of optimization with image_optim, the extra compression that picopt and ImageOptim achieve is quite small. Unless you have a lot of time and processing power, using multiple image optimizers is probably overkill.

The Results (Or, Is This Even Worth It?)

The settings I’m recommending are, admittedly, complicated, but they are absolutely worthwhile for your users. When I set out to do these tests, I did so hoping that I’d be able to drastically reduce file size without sacrificing image quality. I’m happy to report that, using the settings described above, I was successful.

On average, my recommended settings and optimizations reduced file sizes by 35% compared to Photoshop’s “Save for Web”:

Savings compared to Photoshop Creative Cloud
Condition File size: mean File size: % difference
My settings, with optimization 218,274 bytes
My settings, without optimization 259,852 bytes 19.05%
Photoshop CC, with optimization 260,305 bytes 19.28%
Photoshop CC, without optimization 299,710 bytes 35.26%

My settings without optimization even beat Photoshop’s output with optimization!

Compared to ImageMagick’s default image resizing, my recommendations resulted in file sizes that were 82% smaller on average:

Savings compared to ImageMagick defaults
Condition File size: mean File size: % difference
My settings, with optimization 218,274 bytes
My settings, without optimization 259,852 bytes 19.05%
-resize 397,588 bytes 82.15%

Compared to WordPress’s default image resizing (which uses ImageMagick under the hood), my recommendations resulted in file sizes that were 77% smaller on average:

Savings compared to WordPress
Condition File size: mean File size: % difference
My settings, with optimization 218,274 bytes
My settings, without optimization 259,852 bytes 19.05%
WordPress7014* 385,795 bytes 76.75%
* Simulation using ImageMagick with the settings that these CMS’ use by default. The specific settings used can be found in the GitHub repository for these tests7971.

Compared to other CMS’ and tools that use ImageMagick, my recommendations resulted in file sizes that were up to 144% smaller:

Savings compared to other tools
Condition File size: mean File size: % difference
My settings, with optimization 218,274 bytes
My settings, without optimization 259,852 bytes 19.05%
CodeIgniter72/ExpressionEngine73* 340,461 bytes 55.98%
TYPO3.CMS74* 359,112 bytes 64.52%
Drupal7515* 397,588 bytes 82.15%
Perch76* 416,790 bytes 90.95%
Craft CMS77* 425,259 bytes 94.83%
grunt-responsive-images78 533,030 bytes 144.20%
* Simulation using ImageMagick with the settings that these CMS’ use by default. The specific settings used can be found in the GitHub repository for these tests7971.

And remember, this is all with the images being visually indistinguishable from the Photoshop output, on average.

Using the settings I described above can get you huge file size savings without hurting quality. This can be a huge boon to your website’s performance!

How To Implement This In Your Projects

I hope the benefits of using this technique are obvious. Luckily for you, the hard part — figuring all of this out — is all done. Despite the apparent complexity of the recommended settings, implementing this in your own projects can be fairly quick and easy. Although running this whopper of a command from the terminal every time you want to resize an image may be inconvenient, there are simpler options that require very little muss or fuss.

bash shell

Most command-line shells allow you to setup aliases and functions for complicated commands. If you use a bash shell, you can add a function to your .bash_aliases (or .bashrc) file that acts as an alias for my recommended command:

smartresize() {
   mogrify -path $3 -filter Triangle -define filter:support=2 -thumbnail $2 -unsharp 0.25x0.08+8.3+0.045 -dither None -posterize 136 -quality 82 -define jpeg:fancy-upsampling=off -define png:compression-filter=5 -define png:compression-level=9 -define png:compression-strategy=1 -define png:exclude-chunk=all -interlace none -colorspace sRGB $1
}

Then, you can call it like this:

smartresize inputfile.png 300 outputdir/

Node.js

An npm package called, unsurprisingly, imagemagick80 allows you to use ImageMagick via Node.js81. If you’re using this module, you can add resizing using my recommended settings like this:

var im = require('imagemagick');

var inputPath = 'path/to/input';
var outputPath = 'path/to/output';
var width = 300; // output width in pixels

var args = [
   inputPath,
   '-filter',
   'Triangle',
   '-define',
   'filter:support=2',
   '-thumbnail',
   width,
   '-unsharp 0.25x0.25+8+0.065',
   '-dither None',
   '-posterize 136',
   '-quality 82',
   '-define jpeg:fancy-upsampling=off',
   '-define png:compression-filter=5',
   '-define png:compression-level=9',
   '-define png:compression-strategy=1',
   '-define png:exclude-chunk=all',
   '-interlace none',
   '-colorspace sRGB',
   '-strip',
   outputPath
];

im.convert(args, function(err, stdout, stderr) {
   // do stuff
});

Grunt

If you use Grunt8216 as a task runner, good news: I’ve built a Grunt task named grunt-respimg9283 (npm84) that handles everything I’ve described above. You can include it in your projects by running:

npm install grunt-respimg --save-dev

Then, you can run it in your Grunt file like this:

grunt.initConfig({
  respimg: {
    default: {
      options: {
        widths: [200, 400]
      },
      files: [{
        expand: true,
        cwd: 'src/img/',
        src: ['**.{gif,jpg,png,svg}'],
        dest: 'build/img/'
      }]
    }
  },
});
grunt.loadNpmTasks('grunt-respimg');

PHP

PHP85 has ImageMagick integration called Imagick86 that makes it relatively easy to run ImageMagick operations from within your PHP scripts. Unfortunately, Imagick is a bit limited and doesn’t let you do some things that I recommend, like setting a resampling filter to be used with the thumbnail function.

But, again, you’re in luck: I’ve created a composer package called php-respimg9387 (packagist88) that handles everything described above. You can include it in your projects with Composer89 by running:

composer require nwtn/php-respimg

Then, you can resize your images like this:

require_once('vendor/autoload.php');
use nwtnRespimg as Respimg;
$image = new Respimg($input_filename);
$image->smartResize($output_width, 0, false);
$image->writeImage($output_filename);

Content Management Systems

If you use a CMS, you might want to take advantage of these savings for the thumbnails and other resized images that get generated when users upload images. A few options are available to you.

If your CMS is built on PHP, you could bake the PHP stuff above into a theme or plugin. However, if your PHP-based CMS happens to be WordPress, then there’s no need for you to do that work: This is now integrated into the Responsive Issues Community Group’s plugin RICG Responsive Images9490 as an experimental feature. After you install the plugin, all you’ll need to do to activate these ImageMagick settings is add the following lines to your functions.php file:

function custom_theme_setup() {
   add_theme_support( 'advanced-image-compression' );
}
add_action( 'after_setup_theme', 'custom_theme_setup' );

If you don’t use WordPress and don’t want to try to hack this into your CMS, most CMS’ include some way to modify image defaults (especially for quality). You might be able to get a lot of these benefits with a few simple changes to your CMS’ configuration. Check out the documentation and see what options are available to you.

Performance

The settings I’m recommending are obviously far more complex than simply using -resize, and this complexity brings a performance hit with it. Using my recommendations will take longer and use more resources on your computer or server. In my tests, I found that memory and CPU usage peaks were comparable but that my settings took an average of 2.25 times longer to render an image than from just using -resize alone.

Conclusion

As designers and developers, we have an enormous amount of power to shape how — and how well — the web works. One of the biggest impacts we can have is to make our websites more performant, which will improve our users’ experiences and even make our content available to whole new markets91. Cutting image weight is a relatively simple and hugely impactful way to increase performance, and I hope the information outlined above helps you make a difference to your users.

Links

Thank you to Mat Marquis for reviewing a draft of this article.

(da, ml, al)

Footnotes

  1. 1 http://www.smashingmagazine.com/2014/05/14/responsive-images-done-right-guide-picture-srcset/
  2. 2 http://www.smashingmagazine.com/2014/02/03/one-solution-to-responsive-images/
  3. 3 https://twitter.com/tessthornton/status/565960345467252739
  4. 4 http://imagemagick.org/
  5. 5 http://httparchive.org/interesting.php?a=All&l=May%2015%202015
  6. 6 http://whatdoesmysitecost.com/
  7. 7 http://www.smashingmagazine.com/wp-content/uploads/2015/06/01-httparchive-opt.png
  8. 8 http://httparchive.org//
  9. 9 http://www.smashingmagazine.com/wp-content/uploads/2015/06/01-httparchive-opt.png
  10. 10 http://responsiveimages.org/
  11. 11 http://libgd.github.io/
  12. 12 http://www.graphicsmagick.org/
  13. 13 http://imagemagick.org/
  14. 14 https://wordpress.org/
  15. 15 https://www.drupal.org/
  16. 16 http://gruntjs.com/
  17. 17 http://brew.sh/
  18. 18 http://imagemagick.org/script/binary-releases.php
  19. 19 http://www.smashingmagazine.com/wp-content/uploads/2015/06/02-squares-opt.png
  20. 20 http://www.smashingmagazine.com/wp-content/uploads/2015/06/02-squares-opt.png
  21. 21 http://www.smashingmagazine.com/wp-content/uploads/2015/06/03-square-background-opt.png
  22. 22 http://www.smashingmagazine.com/wp-content/uploads/2015/06/03-square-background-opt.png
  23. 23 http://www.smashingmagazine.com/wp-content/uploads/2015/06/04-square-nearestneighbour-opt.png
  24. 24 http://www.smashingmagazine.com/wp-content/uploads/2015/06/04-square-nearestneighbour-opt.png
  25. 25 http://www.smashingmagazine.com/wp-content/uploads/2015/06/05-nearest-neighbour-opt.png
  26. 26 http://www.smashingmagazine.com/wp-content/uploads/2015/06/05-nearest-neighbour-opt.png
  27. 27 http://www.smashingmagazine.com/wp-content/uploads/2015/06/06-circles-bilinear-opt.png
  28. 28 http://www.smashingmagazine.com/wp-content/uploads/2015/06/06-circles-bilinear-opt.png
  29. 29 http://www.imagemagick.org/script/command-line-options.php
  30. 30 https://github.com/nwtn/image-resize-tests
  31. 31 http://en.wikipedia.org/wiki/Structural_similarity
  32. 32 http://www.radware.com/neurostrata-fall2014/
  33. 33 http://www.radware.com/
  34. 34 http://www.imagemagick.org/discourse-server/viewtopic.php?f=3&t=27177
  35. 35 http://www.smashingmagazine.com/wp-content/uploads/2015/06/07-functions-opt.jpg
  36. 36 http://commons.wikimedia.org/wiki/File:Lesser_Sooty_Owl_at_Bonadio%27s_Mabi_Wildlife_Reserve.jpg
  37. 37 http://www.smashingmagazine.com/wp-content/uploads/2015/06/07-functions-opt.jpg
  38. 38 http://johncostella.webs.com/magic/
  39. 39 http://en.wikipedia.org/wiki/Gaussian_blur
  40. 40 https://www.pinterest.com/pin/445363850621483734/
  41. 41 http://www.smashingmagazine.com/wp-content/uploads/2015/06/08-owl-opt.jpg
  42. 42 http://commons.wikimedia.org/wiki/File:Lesser_Sooty_Owl_at_Bonadio%27s_Mabi_Wildlife_Reserve.jpg
  43. 43 http://www.smashingmagazine.com/wp-content/uploads/2015/06/08-owl-opt.jpg
  44. 44 http://www.smashingmagazine.com/wp-content/uploads/2015/06/09-posterization-opt.jpg
  45. 45 http://commons.wikimedia.org/wiki/File:Lesser_Sooty_Owl_at_Bonadio%27s_Mabi_Wildlife_Reserve.jpg
  46. 46 http://www.smashingmagazine.com/wp-content/uploads/2015/06/09-posterization-opt.jpg
  47. 47 http://www.smashingmagazine.com/wp-content/uploads/2015/06/10-dithering-opt.jpg
  48. 48 http://commons.wikimedia.org/wiki/File:Lesser_Sooty_Owl_at_Bonadio%27s_Mabi_Wildlife_Reserve.jpg
  49. 49 http://www.smashingmagazine.com/wp-content/uploads/2015/06/10-dithering-opt.jpg
  50. 50 http://www.smashingmagazine.com/wp-content/uploads/2015/06/11-dithering-bug-opt.png
  51. 51 http://pixabay.com/en/lady-nurse-spectacled-woman-female-311672/
  52. 52 http://www.smashingmagazine.com/wp-content/uploads/2015/06/11-dithering-bug-opt.png
  53. 53 http://www.smashingmagazine.com/wp-content/uploads/2015/06/12-colourspaces-opt.png
  54. 54 http://commons.wikimedia.org/wiki/File:Colorspace.png
  55. 55 http://www.smashingmagazine.com/wp-content/uploads/2015/06/11-dithering-bug-opt.png
  56. 56 http://www.w3.org/TR/css3-color/
  57. 57 http://www.w3.org/TR/SVG11/single-page.html
  58. 58 https://developers.google.com/speed/webp/docs/riff_container
  59. 59 http://www.w3.org/TR/PNG/
  60. 60 http://www.libpng.org/pub/png/book/chapter09.html
  61. 61 http://commons.wikimedia.org/wiki/File:Lesser_Sooty_Owl_at_Bonadio%27s_Mabi_Wildlife_Reserve.jpg
  62. 62 http://en.wikipedia.org/wiki/Adam7_algorithm
  63. 63 http://commons.wikimedia.org/wiki/File:Adam7_passes.gif
  64. 64 http://blog.patrickmeenan.com/2013/06/progressive-jpegs-ftw.html
  65. 65 http://www.radware.com/
  66. 66 http://www.radware.com/neurostrata-fall2014/
  67. 67 https://github.com/toy/image_optim
  68. 68 https://github.com/ajslater/picopt
  69. 69 https://imageoptim.com/
  70. 70 https://wordpress.org/
  71. 71 https://github.com/nwtn/image-resize-tests/tree/no-optimization/test38-cms-comparison#settings-used-for-this-simulation
  72. 72 http://www.codeigniter.com/
  73. 73 https://ellislab.com/expressionengine
  74. 74 https://typo3.org/
  75. 75 https://www.drupal.org/
  76. 76 http://grabaperch.com/
  77. 77 https://buildwithcraft.com/
  78. 78 https://github.com/andismith/grunt-responsive-images
  79. 79 https://github.com/nwtn/image-resize-tests/tree/no-optimization/test38-cms-comparison#settings-used-for-this-simulation
  80. 80 https://www.npmjs.com/package/imagemagick
  81. 81 https://nodejs.org/
  82. 82 http://gruntjs.com/
  83. 83 https://github.com/nwtn/grunt-respimg
  84. 84 https://www.npmjs.com/package/grunt-respimg
  85. 85 http://php.net/
  86. 86 http://php.net/manual/en/book.imagick.php
  87. 87 https://github.com/nwtn/php-respimg
  88. 88 https://packagist.org/packages/nwtn/php-respimg
  89. 89 https://getcomposer.org/
  90. 90 https://wordpress.org/plugins/ricg-responsive-images/
  91. 91 http://blog.chriszacharias.com/page-weight-matters
  92. 92 https://github.com/nwtn/grunt-respimg
  93. 93 https://github.com/nwtn/php-respimg
  94. 94 https://wordpress.org/plugins/ricg-responsive-images/

The post Efficient Image Resizing With ImageMagick appeared first on Smashing Magazine.

Categories: Others Tags:

Efficient Image Resizing With ImageMagick

June 25th, 2015 No comments
HTTP archive pie chart of average bytes per page by content type

Responsive1images2 have been keeping us on our toes for quite some time, and now that they are getting traction in browsers, they come with a scary problem: the need to efficiently resize all our image assets. The way responsive images work is that an appropriately sized image is sent to each user — small versions for users on small screens, big versions for users on big screens.

It’s fantastic for web performance, but we have to face the grim reality that serving different sizes of images to different users means that we first need to create all of those different files, and that can be a huge pain3.

Many tools out there automate image resizing, but too often they create large files that cancel out the performance benefits that responsive images are supposed to deliver. In this article, we’ll see how we can use ImageMagick134 — an open-source command-line graphics editor — to quickly resize your images, while maintaining great visual quality and really tiny file sizes.

Big Images == Big Problem

The average web page is about 2 MB5 in size, and about two thirds of that weight is from images. At the same time, millions of people are accessing the Internet on 3G-or-worse connections that make a 2 MB website a horror show to use. Even on a fast connection, a 2 MB website can wreak havoc on your users’ data plans and cost them real money6. Improving web performance and giving a better experience to our users is our job as developers and designers.

7
The average web page is 2,099 KB, 1,310 KB of which comes from images. (Image: HTTP Archive8) (View large version9)

Responsive images10 to the rescue! Right? Well, yes, but first we have to generate our responsive image assets, and we have to make sure those assets look good and have a small enough footprint to improve the website’s performance.

For a very small website, saving a few different sizes of each image directly in our image editor is trivial — Photoshop even provides a handy “Save for Web” option that keeps file sizes low. But what about a large website with a lot of images? An online store, for example, might have hundreds or thousands of image assets, and having to create different sizes of each of these is an enormous task.

ImageMagick

This is where automated image resizing comes in handy. A bunch of tools out there do this, including GD11 and GraphicsMagick12, but ImageMagick134 strikes a good balance between power and availability in hosting environments. ImageMagick has been around for almost 25 years and is a full-fledged command-line image editor. It is widely supported by content management systems (CMS) such as WordPress7014 and Drupal7515, integrated with task runners such as Grunt8216, and used on its own to automate image editing — including resizing.

It’s also available on desktop systems (Mac, Windows and Linux). If you use Homebrew17 on a Mac, you can install it like this:

brew install imagemagick

Otherwise, look for it in your favorite package manager, or download it directly from the ImageMagick website18.

ImageMagick provides a fast, simple way to automate image resizing. Unfortunately, with the default settings, the resized files it outputs are often really big — sometimes bigger than the inputted image, even though the output has fewer pixels. These big files completely negate the performance gains you’d expect to get from responsive images and, in fact, can make things worse for your users than if you’d simply loaded the huge unshrunk assets.

Below, I’ll describe why this problem exists and show you how to change ImageMagick’s default settings to solve this problem and get small, great-looking images.

How Image Resizing Works

The best way to solve the problem is to understand why it’s happening, and that means understanding the basics of how image resizing works.

By definition, when a computer resizes an image, the number of pixels in that image will change. If the image is being enlarged, the output will have more pixels than the input; if the image is being shrunk, the output will have fewer pixels than the input. The challenge is in figuring out the best way to store the original image’s content in this different number of pixels. In other words, we need to figure out the best way to add or remove pixels without changing what the image looks like.

Although not as common a use case, image upsampling (i.e. making images larger) can be a little easier to visualize, so let’s start with that. Consider an image of a blue 4 × 4 pixel square that we want to double in size to 8 × 8 pixels. What we’re doing is taking the same image and applying it to a new pixel grid; this is called resampling and is usually what we mean when we talk about resizing images. To resample our 4 × 4 blue square to 8 × 8 pixels, we need to add 48 extra pixels somewhere. Those pixels will need some color value, and the process of determining that color value is called interpolation. When you’re resampling, the algorithm for determining how the interpolation works is called a resampling filter.

19
How do we resample a 4 × 4 pixel square to an 8 × 8 pixel grid? (View large version20)

We could use all sorts of resampling filters and interpolation methods to figure out those 48 extra pixels. The absolute simplest thing we could do is to add four more rows and four more columns of pixels in some arbitrary color — say, red. This is called background interpolation, because the empty pixels are simply exposing a background color (red). This is what you’re doing in Photoshop when you resize using “Image” ? “Canvas Size,” instead of “Image” ? “Image Size.”

This, of course, is a terrible outcome when we want to resize an image: we don’t perceive the new outputted image to really look like the original inputted image at all; the original square is blue, the new one is blue and red. Background interpolation is only possible when adding pixels (i.e. when making the image bigger or when upsampling), and even then it is essentially useless for resizing, except as a means to show where the new pixels are.

A pink and blue square21
Background interpolation. (View large version22)

Another very simple interpolation method is to make our new pixels the same color as their neighboring pixels; this is called nearest-neighbor interpolation. This produces a much better result than background interpolation, especially for a simple square like this.

A blue square23
Nearest-neighbor interpolation: upsampling a square. (View large version24)

Downsampling (i.e. making the image smaller) with nearest-neighbor interpolation is not as intuitive as upsampling, but it helps to remember that the math involved is OK with fractional pixels. First, the new pixel grid gets applied to the orignal image. Because there are fewer pixels to store the image information, some of the pixels in this new grid will contain multiple colors; in the example below, some pixels contain both blue and white.

Outputting the image in this way to the physical pixels in the real world isn’t possible, though — each pixel can be only one color. The final color of each pixel in the new grid is determined by the color at its center point. In other words, that center point is sampled to determine the final color, which is why nearest-neighbor interpolation is sometimes called point sampling.

Four images: a circle; an 8×8 pixel grid; the grid overlayed on top of the circle with the center marked; and the resized circle, which is blocky and not very circular25
Nearest-neighbor interpolation: downsampling a circle. (View large version26)

For anything more complicated than a line or square, nearest-neighbor interpolation produces very jagged, blocky images. It’s fast and creates small files but doesn’t look very good.

Most resampling filters use some sort of variation on nearest-neighbor interpolation — they sample multiple points to determine the color of a pixel and use math to try to come up with a smart compromise for those values. Bilinear interpolation, for example, creates a weighted average of colors. It produces much nicer results than nearest-neighbor interpolation.

Two circles27
Bilinear interpolation. (View large version28)

One way that resampling — and the specific resampling filter used — can affect file size is by affecting the colors in the image. Bilinear interpolation gives the circle smooth edges, but that means giving the image more colors. The original blue circle has two colors, blue and white. The resized circle has more — some pixels are a pale bluey-white. All else being equal, more colors in an image will make the file size bigger. This is one reason why resizing an image to have fewer pixels sometimes gives it more bytes.

What All This Means for Us

In order to make our outputted images smaller, we’ll want to look at ways to reduce the number of colors without sacrificing quality. Choosing an appropriate resampling filter has one of the biggest effects, but other settings can affect the number of colors in the output as well. I’ll also discuss settings that control file compression and quality and that eliminate extraneous data.

Optimal Settings For ImageMagick

ImageMagick Basics

ImageMagick has a ton of options and functions29, and finding a good combination of these can be tricky.

Two main ImageMagick settings are of interest to us, convert and mogrify. Both of these perform similar operations, but mogrify is intended to be used with multiple files at once, while convert handles only one image at a time.

A simple ImageMagick operation might look like this:

convert input.jpg -resize 300 output.jpg

This says that we want ImageMagick’s convert function to take input.jpg and resize it to 300 pixels wide, and then save that to output.jpg. The -resize 300 part is an example of one of ImageMagick’s many built-in functions. Each function uses the same format: -functionName option.

Using mogrify is similar, but with the syntax reordered a bit:

mogrify -path output/ -resize 300 *.jpg

This says that we want ImageMagick’s mogrify function to take all JPEG files in the current directory (*.jpg), resize them to 300 pixels wide and then save them in the output directory.

Functions can be combined for more complex results:

convert input.jpg -resize 300 -quality 75 output.jpg

As before, this resizes input.jpg to 300 pixels wide, but this time it also sets the JPEG quality to 75 before saving it to output.jpg.

I’ve performed hundreds of tests30 to see which combinations of functions and options produce the smallest results at an acceptable quality.

Testing and Results

I wanted to keep the file size as low as possible but keep the quality high — indistinguishable from Photoshop’s “Save for Web.” To do this, I used both a subjective quality measure — my own opinion on whether the output looks good — and an objective quality measure — structural dissimilarity31 (DSSIM). DSSIM compares two images — in this case, my test image and a control generated by Photoshop’s “Save for Web” — and generates a score. The lower the score, the more the images resemble each other; a score of zero means they are identical. To make sure test images look the same as Photoshop’s output, I wanted a mean DSSIM score of 0.0075 or lower. In research released last year32, RadWare33 found that image pairs with a DSSIM score of 0.015 were indistinguishable to their test users.

To make sure the results weren’t biased by outliers, I tested on 40 images that are a mixture of JPEGs and PNGs; photos, drawings and line art; color and monochrome; transparent and opaque. I also tested at three output sizes (300, 600 and 1200 pixels wide) from a variety of input sizes. Finally, I tested both with and without image optimization.

From my tests, running ImageMagick with the following settings produced the smallest results, while generally being visually indistinguishable from Photoshop’s output:

mogrify -path OUTPUT_PATH -filter Triangle -define filter:support=2 -thumbnail OUTPUT_WIDTH -unsharp 0.25x0.25+8+0.065 -dither None -posterize 136 -quality 82 -define jpeg:fancy-upsampling=off -define png:compression-filter=5 -define png:compression-level=9 -define png:compression-strategy=1 -define png:exclude-chunk=all -interlace none -colorspace sRGB -strip INPUT_PATH

That’s a lot to take in, so let’s go through each bit and see what it means.

Mogrify vs. Convert

As mentioned, ImageMagick provides two similar tools for manipulating images: convert is the basic image editor and works on one image at a time; mogrify is mostly used for batch image manipulation. In an ideal world, these two tools would produce identical results; unfortunately, that’s not the case — convert has a bug34 that makes it ignore one of the settings I recommend using (the -define jpeg:fancy-upsampling=off setting, discussed below), so using mogrify is better.

Resampling

Choosing a resampling filter in ImageMagick is surprisingly complicated. There are three ways you can do this:

  • with the resizing function you choose,
  • with the -filter setting,
  • or with the -interpolate setting.
Example output from twelve different resizing functions35
One of these things just doesn’t belong here, but the rest look pretty much the same, which is why I used an objective quality measure. (Image: Richard Fisher6148454236) (View large version37)

The most obvious resizing function to use is -resize, but it creates files that are too large. I looked at 11 different functions and found that -thumbnail does the best job of optimizing quality and file size. In most cases, the -thumbnail function uses a three-step process to resize images:

  1. It resizes the image to five times the output size using the -sample function, which has its own built-in resampling filter that’s similar to the nearest-neighbor approach discussed above.
  2. It resizes the image to its final output size using the basic -resize filter.
  3. It strips meta data from the image.

This means that if we were resizing an image to be 500 pixels wide, -thumbnail would first resize it to 2,500 pixels wide using -sample; the result might be blocky and pixelated, as we saw in the examples above, but the operation would be fast and would produce a result with a small file size. Then, ImageMagick would resize this image from 2,500 pixels wide to 500 pixels wide using -resize. This smooths out the blockiness, but the file size stays pretty low. Finally, ImageMagick would remove meta data to get an even smaller file.

The second way to choose a resampling filter in ImageMagick is with the -filter setting. Some resizing functions (such as -sample) have a built-in resampling function that’s always used, but others (such as -resize) have defaults that can be overridden with -filter. The -filter setting gets used in -thumbnail‘s second step, because that step uses -resize.

I tested 31 different settings for -filter and got the best results with Triangle. The Triangle resampling filter is also known as bilinear interpolation, which I discussed above. It determines pixel color by looking at a support area of neighboring pixels and produces a weighted average of their colors. I found it best to specify this support area at two pixels using the -define filter:support=2 setting.

The third way to choose a resampling filter, the -interpolate setting, is ignored by -thumbnail, so it’s not needed here.

In addition to the settings above, by default ImageMagick also uses something called JPEG fancy upsampling38, an algorithm that tries to produce better-looking JPEGs. I’ve found that it produces larger files and that the quality difference is negligible, so I recommend turning it off with -define jpeg:fancy-upsampling=off.

Sharpening

Images pretty often get a little blurry when resized, so programs such as Photoshop will often apply some sharpening afterwards to make the images a little crisper. I recommend using an unsharp filter — which, despite its name, actually does sharpen the image — with the setting -unsharp 0.25x0.25+8+0.065.

Unsharp filters work by first applying a Gaussian blur39 to the image. The first two values for the unsharp filter are the radius and sigma, respectively — in this case, both have a value of 0.25 pixels. These values are often the same and, combined, tell ImageMagick how much to blur the image. After the blur is applied, the filter compares the blurred version to the original, and in any areas where their brightness differs by more than a given threshold (the last value, 0.065), a certain amount of sharpening is applied (the third value, 8). The exact meanings of the threshold and numerical amounts aren’t very important; just remember that a higher threshold value means that sharpening will be applied less often, and a higher numerical amount means that the sharpening will be more intense wherever it is applied.

Color Reduction

I mentioned that one of the biggest reasons why resized images get bloated is because of all the extra colors in them. So, try to reduce the number of colors — but not so much that the quality suffers.

One way to reduce colors is with posterization, a process in which gradients are reduced to bands of solid color. Posterization reduces colors to a certain number of color levels — that is, the number of colors available in each of the red, green and blue color channels that images use. The total number of colors in the final image will be a combination of the colors in these three channels.

Posterization can drastically reduce file size, but can also drastically change how an image looks. With only a few color levels, it creates an effect like what you might see in 1970s rock posters40, with a few discrete bands of color. With many color levels — for example, 136, as I’m suggesting — you get a smaller file without losing much image quality.

Close up of an owl with reduced colors41
Original image. (Image: Richard Fisher6148454236) (View large version43)
Close up of an owl with reduced colors44
Posterization reduces the colors in the image. (Image: Richard Fisher6148454236) (View large version46)

Dithering is a process that is intended to mitigate color banding by adding noise into the color bands to create the illusion that the image has more colors. In theory, dithering seems like a good idea when you posterize; it helps the viewer perceive the result as looking more like the original.

Two images of an old woman, the second full of image rendering artifacts47
Dithering. (Image: Richard Fisher6148454236) (View large version49)

Unfortunately, ImageMagick has a bug that ruins images with transparency when dithering is used like this. So, it’s best to turn dithering off with -dither None. Luckily, even without dithering, the posterized images still look good.

Two images of an old woman, the second full of image rendering artifacts50
ImageMagick dithering bug. (Image: Nemo51) (View large version5552)

Color Space

While not strictly a matter of color reduction, setting an image’s color space is a related concept. The color space defines what colors are available for an image. The image below shows that the ProPhoto RGB color space contains more colors than the Adobe RGB color space, which in turn contains more colors than the sRGB color space. All of these contain fewer colors than are visible to the human eye.

Map that compares how much of the color spectrum is covered by different color spaces; sRGB covers the least53
Color spaces. (Image: Cpesacreta54) (View large version5552)

sRGB was created to be the one true king of color spaces on the Internet. It has been endorsed by the W3C and other standards bodies; it is the required color space in the CSS Color Module Level 356 and the SVG specification57 and is the assumed color space of the WebP58 specification; and it is explicitly referenced in the PNG specification59. It’s also the default color space in Photoshop. In short, sRGB is the color space of choice for the web platform, and, assuming you want your images to render predictably, using it is probably a good idea.

Quality and Compression

With lossy image formats such as JPEG, quality and compression go hand in hand: the higher the compression, the lower the quality and the lower the file size. We could drastically reduce file size by setting a high JPEG compression factor, but this would also drastically reduce quality. A balance is needed.

When I was doing my tests, the control images I created with Photoshop had a JPEG quality setting of high, or 60. I’ve found that this setting works well for me and strikes the right balance between quality and file size. However, in my ImageMagick settings, I’m recommending -quality 82. Why?

It turns out that JPEG quality scales are not defined in a specification or standard, and they are not uniform across encoders. A quality of 60 in Photoshop might be the same as a quality of 40 in one program, quality B+ in another and quality fantastico in a third. In my tests, I found that Photoshop’s 60 is closest to -quality 82 in ImageMagick.

For non-lossy image formats, such as PNG, quality and compression are not related at all. High compression doesn’t change how an image looks at all and only comes at the expense of processing load (in terms of CPU usage, memory usage and processing time). Assuming that our computers can handle this load, there’s no reason not to max out PNG compression.

PNG compression in ImageMagick can be configured with three settings, -define png:compression-filter, -define png:compression-level and -define png:compression-strategy. Compression filtering60 is a pre-compression step that reorganizes the image’s data so that the actual compression is more efficient; I got the best results using adaptive filtering (-define png:compression-filter=5). Compression level is the amount of compression that gets applied; I recommend maxing this out to 9 (-define png:compression-level=9). Finally, the compression strategy setting determines the actual algorithm that’s used to compress the files; I got the best result with the default compression strategy (-define png:compression-strategy=1).

Meta Data

In addition to the actual image data, image files can contain meta data: information about the image, such as when it was created and the device that created it. This extra information could take up space without providing any benefit to our users and should usually be removed. Above, when describing the -thumbnail function that handles the actual resizing of the image, I mentioned that its third step involves stripping meta data. Even though that’s true, -thumbnail doesn’t remove all of the meta data, and there are gains to be had by using -strip and -define png:exclude-chunk=all as well. Neither of these should affect quality at all.

Progressive Rendering

JPEGs and PNGs can be saved to use either progressive or sequential rendering. Sequential rendering is usually the default: The image will load pixels row by row from top to bottom. Progressive rendering means the image is delivered and rendered in stages.

For JPEGs, progressive rendering can happen in any number of stages, as determined when the file is saved. The first stage will be a very low-resolution version of the full image; at each subsequent stage, a higher-resolution version is delivered until, in the last stage, the full-quality version is rendered.

An owl, rendering at progressively higher quality
Progressive JPEG simulation. (Image: Richard Fisher6148454236)

PNGs use a type of progressive rendering called Adam7 interlacing62, in which the pixels of the image are delivered in seven stages based on an 8 × 8 pixel grid.

Pixels being rendered in seven passes
Adam7 interlacing. (Image: CountingPine63)

Both types of progressive rendering can be controlled in ImageMagick using the -interlace setting. But should progressive rendering be turned on or not?

For both JPEGs and PNGs, progressive rendering increases the file size, but for a long time conventional wisdom held that it was worth turning on64 because it delivered a better experience to the user. The idea is that even if the full, perfect image doesn’t load quite as quickly, users would be able to see something earlier, and that something is probably better than nothing.

Last year, though, Radware65 released research on progressive JPEGs66 that shows users actually tend to prefer sequential image rendering. This is just one study (and one that hasn’t gone through a formal peer review process), but the results are interesting. Radware’s results, combined with the fact that sequential images have smaller file sizes, lead me to recommend the -interlace none setting in ImageMagick.

Image Optimization

I mentioned above that I ran tests both with and without image optimization. All of the settings I’ve described so far are what I’d recommend if you’re not optimizing your images. If you can optimize them, though, my recommendations would change slightly: I found that slightly different -unsharp settings work better (-unsharp 0.25x0.08+8.3+0.045 versus -unsharp 0.25x0.25+8+0.065 without optimization) and that there’s no need to use -strip.

mogrify -path OUTPUT_PATH -filter Triangle -define filter:support=2 -thumbnail OUTPUT_WIDTH -unsharp 0.25x0.08+8.3+0.045 -dither None -posterize 136 -quality 82 -define jpeg:fancy-upsampling=off -define png:compression-filter=5 -define png:compression-level=9 -define png:compression-strategy=1 -define png:exclude-chunk=all -interlace none -colorspace sRGB INPUT_PATH

A lot of different image optimizers are out there. I tested image_optim67, picopt68 and ImageOptim69, all of which run images through a battery of different optimization steps. I tested these tools both individually and in combination, and I found that the best results come from running files through all three, in the order listed above. That said, there are diminishing returns: After the first round of optimization with image_optim, the extra compression that picopt and ImageOptim achieve is quite small. Unless you have a lot of time and processing power, using multiple image optimizers is probably overkill.

The Results (Or, Is This Even Worth It?)

The settings I’m recommending are, admittedly, complicated, but they are absolutely worthwhile for your users. When I set out to do these tests, I did so hoping that I’d be able to drastically reduce file size without sacrificing image quality. I’m happy to report that, using the settings described above, I was successful.

On average, my recommended settings and optimizations reduced file sizes by 35% compared to Photoshop’s “Save for Web”:

Savings compared to Photoshop Creative Cloud
Condition File size: mean File size: % difference
My settings, with optimization 218,274 bytes
My settings, without optimization 259,852 bytes 19.05%
Photoshop CC, with optimization 260,305 bytes 19.28%
Photoshop CC, without optimization 299,710 bytes 35.26%

My settings without optimization even beat Photoshop’s output with optimization!

Compared to ImageMagick’s default image resizing, my recommendations resulted in file sizes that were 82% smaller on average:

Savings compared to ImageMagick defaults
Condition File size: mean File size: % difference
My settings, with optimization 218,274 bytes
My settings, without optimization 259,852 bytes 19.05%
-resize 397,588 bytes 82.15%

Compared to WordPress’s default image resizing (which uses ImageMagick under the hood), my recommendations resulted in file sizes that were 77% smaller on average:

Savings compared to WordPress
Condition File size: mean File size: % difference
My settings, with optimization 218,274 bytes
My settings, without optimization 259,852 bytes 19.05%
WordPress7014* 385,795 bytes 76.75%
* Simulation using ImageMagick with the settings that these CMS’ use by default. The specific settings used can be found in the GitHub repository for these tests7971.

Compared to other CMS’ and tools that use ImageMagick, my recommendations resulted in file sizes that were up to 144% smaller:

Savings compared to other tools
Condition File size: mean File size: % difference
My settings, with optimization 218,274 bytes
My settings, without optimization 259,852 bytes 19.05%
CodeIgniter72/ExpressionEngine73* 340,461 bytes 55.98%
TYPO3.CMS74* 359,112 bytes 64.52%
Drupal7515* 397,588 bytes 82.15%
Perch76* 416,790 bytes 90.95%
Craft CMS77* 425,259 bytes 94.83%
grunt-responsive-images78 533,030 bytes 144.20%
* Simulation using ImageMagick with the settings that these CMS’ use by default. The specific settings used can be found in the GitHub repository for these tests7971.

And remember, this is all with the images being visually indistinguishable from the Photoshop output, on average.

Using the settings I described above can get you huge file size savings without hurting quality. This can be a huge boon to your website’s performance!

How To Implement This In Your Projects

I hope the benefits of using this technique are obvious. Luckily for you, the hard part — figuring all of this out — is all done. Despite the apparent complexity of the recommended settings, implementing this in your own projects can be fairly quick and easy. Although running this whopper of a command from the terminal every time you want to resize an image may be inconvenient, there are simpler options that require very little muss or fuss.

bash shell

Most command-line shells allow you to setup aliases and functions for complicated commands. If you use a bash shell, you can add a function to your .bash_aliases (or .bashrc) file that acts as an alias for my recommended command:

smartresize() {
   mogrify -path $3 -filter Triangle -define filter:support=2 -thumbnail $2 -unsharp 0.25x0.08+8.3+0.045 -dither None -posterize 136 -quality 82 -define jpeg:fancy-upsampling=off -define png:compression-filter=5 -define png:compression-level=9 -define png:compression-strategy=1 -define png:exclude-chunk=all -interlace none -colorspace sRGB $1
}

Then, you can call it like this:

smartresize inputfile.png 300 outputdir/

Node.js

An npm package called, unsurprisingly, imagemagick80 allows you to use ImageMagick via Node.js81. If you’re using this module, you can add resizing using my recommended settings like this:

var im = require('imagemagick');

var inputPath = 'path/to/input';
var outputPath = 'path/to/output';
var width = 300; // output width in pixels

var args = [
   inputPath,
   '-filter',
   'Triangle',
   '-define',
   'filter:support=2',
   '-thumbnail',
   width,
   '-unsharp 0.25x0.25+8+0.065',
   '-dither None',
   '-posterize 136',
   '-quality 82',
   '-define jpeg:fancy-upsampling=off',
   '-define png:compression-filter=5',
   '-define png:compression-level=9',
   '-define png:compression-strategy=1',
   '-define png:exclude-chunk=all',
   '-interlace none',
   '-colorspace sRGB',
   '-strip',
   outputPath
];

im.convert(args, function(err, stdout, stderr) {
   // do stuff
});

Grunt

If you use Grunt8216 as a task runner, good news: I’ve built a Grunt task named grunt-respimg9283 (npm84) that handles everything I’ve described above. You can include it in your projects by running:

npm install grunt-respimg --save-dev

Then, you can run it in your Grunt file like this:

grunt.initConfig({
  respimg: {
    default: {
      options: {
        widths: [200, 400]
      },
      files: [{
        expand: true,
        cwd: 'src/img/',
        src: ['**.{gif,jpg,png,svg}'],
        dest: 'build/img/'
      }]
    }
  },
});
grunt.loadNpmTasks('grunt-respimg');

PHP

PHP85 has ImageMagick integration called Imagick86 that makes it relatively easy to run ImageMagick operations from within your PHP scripts. Unfortunately, Imagick is a bit limited and doesn’t let you do some things that I recommend, like setting a resampling filter to be used with the thumbnail function.

But, again, you’re in luck: I’ve created a composer package called php-respimg9387 (packagist88) that handles everything described above. You can include it in your projects with Composer89 by running:

composer require nwtn/php-respimg

Then, you can resize your images like this:

require_once('vendor/autoload.php');
use nwtnRespimg as Respimg;
$image = new Respimg($input_filename);
$image->smartResize($output_width, 0, false);
$image->writeImage($output_filename);

Content Management Systems

If you use a CMS, you might want to take advantage of these savings for the thumbnails and other resized images that get generated when users upload images. A few options are available to you.

If your CMS is built on PHP, you could bake the PHP stuff above into a theme or plugin. However, if your PHP-based CMS happens to be WordPress, then there’s no need for you to do that work: This is now integrated into the Responsive Issues Community Group’s plugin RICG Responsive Images9490 as an experimental feature. After you install the plugin, all you’ll need to do to activate these ImageMagick settings is add the following lines to your functions.php file:

function custom_theme_setup() {
   add_theme_support( 'advanced-image-compression' );
}
add_action( 'after_setup_theme', 'custom_theme_setup' );

If you don’t use WordPress and don’t want to try to hack this into your CMS, most CMS’ include some way to modify image defaults (especially for quality). You might be able to get a lot of these benefits with a few simple changes to your CMS’ configuration. Check out the documentation and see what options are available to you.

Performance

The settings I’m recommending are obviously far more complex than simply using -resize, and this complexity brings a performance hit with it. Using my recommendations will take longer and use more resources on your computer or server. In my tests, I found that memory and CPU usage peaks were comparable but that my settings took an average of 2.25 times longer to render an image than from just using -resize alone.

Conclusion

As designers and developers, we have an enormous amount of power to shape how — and how well — the web works. One of the biggest impacts we can have is to make our websites more performant, which will improve our users’ experiences and even make our content available to whole new markets91. Cutting image weight is a relatively simple and hugely impactful way to increase performance, and I hope the information outlined above helps you make a difference to your users.

Links

Thank you to Mat Marquis for reviewing a draft of this article.

(da, ml, al)

Footnotes

  1. 1 http://www.smashingmagazine.com/2014/05/14/responsive-images-done-right-guide-picture-srcset/
  2. 2 http://www.smashingmagazine.com/2014/02/03/one-solution-to-responsive-images/
  3. 3 https://twitter.com/tessthornton/status/565960345467252739
  4. 4 http://imagemagick.org/
  5. 5 http://httparchive.org/interesting.php?a=All&l=May%2015%202015
  6. 6 http://whatdoesmysitecost.com/
  7. 7 http://www.smashingmagazine.com/wp-content/uploads/2015/06/01-httparchive-opt.png
  8. 8 http://httparchive.org//
  9. 9 http://www.smashingmagazine.com/wp-content/uploads/2015/06/01-httparchive-opt.png
  10. 10 http://responsiveimages.org/
  11. 11 http://libgd.github.io/
  12. 12 http://www.graphicsmagick.org/
  13. 13 http://imagemagick.org/
  14. 14 https://wordpress.org/
  15. 15 https://www.drupal.org/
  16. 16 http://gruntjs.com/
  17. 17 http://brew.sh/
  18. 18 http://imagemagick.org/script/binary-releases.php
  19. 19 http://www.smashingmagazine.com/wp-content/uploads/2015/06/02-squares-opt.png
  20. 20 http://www.smashingmagazine.com/wp-content/uploads/2015/06/02-squares-opt.png
  21. 21 http://www.smashingmagazine.com/wp-content/uploads/2015/06/03-square-background-opt.png
  22. 22 http://www.smashingmagazine.com/wp-content/uploads/2015/06/03-square-background-opt.png
  23. 23 http://www.smashingmagazine.com/wp-content/uploads/2015/06/04-square-nearestneighbour-opt.png
  24. 24 http://www.smashingmagazine.com/wp-content/uploads/2015/06/04-square-nearestneighbour-opt.png
  25. 25 http://www.smashingmagazine.com/wp-content/uploads/2015/06/05-nearest-neighbour-opt.png
  26. 26 http://www.smashingmagazine.com/wp-content/uploads/2015/06/05-nearest-neighbour-opt.png
  27. 27 http://www.smashingmagazine.com/wp-content/uploads/2015/06/06-circles-bilinear-opt.png
  28. 28 http://www.smashingmagazine.com/wp-content/uploads/2015/06/06-circles-bilinear-opt.png
  29. 29 http://www.imagemagick.org/script/command-line-options.php
  30. 30 https://github.com/nwtn/image-resize-tests
  31. 31 http://en.wikipedia.org/wiki/Structural_similarity
  32. 32 http://www.radware.com/neurostrata-fall2014/
  33. 33 http://www.radware.com/
  34. 34 http://www.imagemagick.org/discourse-server/viewtopic.php?f=3&t=27177
  35. 35 http://www.smashingmagazine.com/wp-content/uploads/2015/06/07-functions-opt.jpg
  36. 36 http://commons.wikimedia.org/wiki/File:Lesser_Sooty_Owl_at_Bonadio%27s_Mabi_Wildlife_Reserve.jpg
  37. 37 http://www.smashingmagazine.com/wp-content/uploads/2015/06/07-functions-opt.jpg
  38. 38 http://johncostella.webs.com/magic/
  39. 39 http://en.wikipedia.org/wiki/Gaussian_blur
  40. 40 https://www.pinterest.com/pin/445363850621483734/
  41. 41 http://www.smashingmagazine.com/wp-content/uploads/2015/06/08-owl-opt.jpg
  42. 42 http://commons.wikimedia.org/wiki/File:Lesser_Sooty_Owl_at_Bonadio%27s_Mabi_Wildlife_Reserve.jpg
  43. 43 http://www.smashingmagazine.com/wp-content/uploads/2015/06/08-owl-opt.jpg
  44. 44 http://www.smashingmagazine.com/wp-content/uploads/2015/06/09-posterization-opt.jpg
  45. 45 http://commons.wikimedia.org/wiki/File:Lesser_Sooty_Owl_at_Bonadio%27s_Mabi_Wildlife_Reserve.jpg
  46. 46 http://www.smashingmagazine.com/wp-content/uploads/2015/06/09-posterization-opt.jpg
  47. 47 http://www.smashingmagazine.com/wp-content/uploads/2015/06/10-dithering-opt.jpg
  48. 48 http://commons.wikimedia.org/wiki/File:Lesser_Sooty_Owl_at_Bonadio%27s_Mabi_Wildlife_Reserve.jpg
  49. 49 http://www.smashingmagazine.com/wp-content/uploads/2015/06/10-dithering-opt.jpg
  50. 50 http://www.smashingmagazine.com/wp-content/uploads/2015/06/11-dithering-bug-opt.png
  51. 51 http://pixabay.com/en/lady-nurse-spectacled-woman-female-311672/
  52. 52 http://www.smashingmagazine.com/wp-content/uploads/2015/06/11-dithering-bug-opt.png
  53. 53 http://www.smashingmagazine.com/wp-content/uploads/2015/06/12-colourspaces-opt.png
  54. 54 http://commons.wikimedia.org/wiki/File:Colorspace.png
  55. 55 http://www.smashingmagazine.com/wp-content/uploads/2015/06/11-dithering-bug-opt.png
  56. 56 http://www.w3.org/TR/css3-color/
  57. 57 http://www.w3.org/TR/SVG11/single-page.html
  58. 58 https://developers.google.com/speed/webp/docs/riff_container
  59. 59 http://www.w3.org/TR/PNG/
  60. 60 http://www.libpng.org/pub/png/book/chapter09.html
  61. 61 http://commons.wikimedia.org/wiki/File:Lesser_Sooty_Owl_at_Bonadio%27s_Mabi_Wildlife_Reserve.jpg
  62. 62 http://en.wikipedia.org/wiki/Adam7_algorithm
  63. 63 http://commons.wikimedia.org/wiki/File:Adam7_passes.gif
  64. 64 http://blog.patrickmeenan.com/2013/06/progressive-jpegs-ftw.html
  65. 65 http://www.radware.com/
  66. 66 http://www.radware.com/neurostrata-fall2014/
  67. 67 https://github.com/toy/image_optim
  68. 68 https://github.com/ajslater/picopt
  69. 69 https://imageoptim.com/
  70. 70 https://wordpress.org/
  71. 71 https://github.com/nwtn/image-resize-tests/tree/no-optimization/test38-cms-comparison#settings-used-for-this-simulation
  72. 72 http://www.codeigniter.com/
  73. 73 https://ellislab.com/expressionengine
  74. 74 https://typo3.org/
  75. 75 https://www.drupal.org/
  76. 76 http://grabaperch.com/
  77. 77 https://buildwithcraft.com/
  78. 78 https://github.com/andismith/grunt-responsive-images
  79. 79 https://github.com/nwtn/image-resize-tests/tree/no-optimization/test38-cms-comparison#settings-used-for-this-simulation
  80. 80 https://www.npmjs.com/package/imagemagick
  81. 81 https://nodejs.org/
  82. 82 http://gruntjs.com/
  83. 83 https://github.com/nwtn/grunt-respimg
  84. 84 https://www.npmjs.com/package/grunt-respimg
  85. 85 http://php.net/
  86. 86 http://php.net/manual/en/book.imagick.php
  87. 87 https://github.com/nwtn/php-respimg
  88. 88 https://packagist.org/packages/nwtn/php-respimg
  89. 89 https://getcomposer.org/
  90. 90 https://wordpress.org/plugins/ricg-responsive-images/
  91. 91 http://blog.chriszacharias.com/page-weight-matters
  92. 92 https://github.com/nwtn/grunt-respimg
  93. 93 https://github.com/nwtn/php-respimg
  94. 94 https://wordpress.org/plugins/ricg-responsive-images/

The post Efficient Image Resizing With ImageMagick appeared first on Smashing Magazine.

Categories: Others Tags:

Infragistics Indigo Studio: Real Rapid Prototyping for Web, Mobile, and Desktop

June 24th, 2015 No comments

Rapid prototyping is an essential way of saving time in our modern age where billions of apps compete for the customer’s attention. Is the great idea you had for just another app actually that great or is it just another failure among the millions of failures in app stores and the web worldwide? Apart from that angle rapid prototyping has always been the easiest and at the same time most impressive way of showing a customer a functional demo of the project you are trying to sell him. Whether it’s development for the web, for mobile or the desktop, you shouldn’t do it without having done a working prototype. Infragistics Indigo Studio is a software that can help you do just that… The History of Prototyping I have created websites since the early nineties. And I have worked with countless clients from different industries around the world. What always was the hardest part in any given project, was the design discussion. Just like any other designer I knew then, we used to squeeze out a quick Photoshop mockup to show it to the client. These mockups were sent by mail, and feedback was given in the same way, except that […]

Categories: Others Tags:

Effective Logo Design, Part 3: How Geometry Influences Logo Design

June 23rd, 2015 No comments
The five basic geometric shapes used in all cultural artwork in order of least to most complex

Galileo knew it. Every ancient culture that left traces of knowledge in their art knew it. Basic shapes compose the fundamental geometry of the universe. We can take credit for a lot of things, but human beings did not invent geometric shapes. We discovered them through the observation of nature1. Understanding basic shapes and their functions have taught us to mark time and space in a variety of ways inspiring mathematics, technology, language and ever-evolving civilization.

“The universe cannot be read until we learn the language in which it is written. It is written in mathematics, and the letters are triangles, circles and other geometrical figures, without which it is humanly impossible to understand a single word.”

– Galileo Galilei

A handful of simple shapes have been used throughout time in the art of all cultures: the circle, intersecting lines, the triangle, the square and the spiral. Cultural anthropologist Angeles Arrien researched and documented commonalities in cultural art forms over several decades and found consistent geometric shapes embedded in all art. She called them the “five universal shapes.”

2
The five basic geometric shapes used in all cultural artwork in order of least to most complex. (View large version3)

Each fundamental shape never varies in its basic function because each unifies purpose with form. A circle rolls freely, lines travel and intersect, a triangle sits securely while pointing away from itself, a four-sided shape is imminently stable, and a spiral curls with elegant persistence. Don’t let the simplicity of these forms fool you. It is because they are so simple that they have the ability to scale consistently and are used as the building blocks of nature and the man-made world. They also provide consistent messaging for a logo.

This three-part series explores fundamental creative strategies for designing effective logos. The first part4 shows how to use symbols, metaphors and the power of intuition. The second part5 shows how to use nature’s patterns in logo design. This last part is about how geometry influences logo design.

A Little Geometry (Goes A Long Way)

The purpose of a logo is to communicate the client in the simplest but most comprehensive way possible. The basic shapes communicate fundamental qualities of the organization in the most immediate way and they are used in design of every ilk — graphic, environmental, interior, product and industrial design, and architecture.

To understand the connections between form and function in each geometric shape, I’ll give an overview of how it is created, how it sets the stage for the next shape, how it appears in nature and the built world, and the kinds of clients it would be a good fit for. The shapes begin simply but become complex as they are developed, just as our experience of living does over time. They are also related to the spatial dimensions we experience through the process of living.

“To me no experience of childhood so reinforced self-confidence in one’s own exploratory faculties as did geometry.”

– Buckminster Fuller

Our senses are responsible for processing an incredible amount of information every moment of every day. Only a small fraction of that information makes it into consciousness because the brain simply can’t process the endless stream generated by the outside world. Because of the sheer quantity of it, most of our experience is absorbed subliminally.

Digital technology has removed much of the tactile experience in just a few decades. But touch has been an important part of how we have understood the world throughout our entire history. Using traditional drawing tools keeps us rooted in the tangible world. So, now and then, be hands-on to get a more comprehensive understanding of what you are creating. Draw, spend time in nature without an agenda, and experiment with geometry by hand so that your design is multifaceted in meaning but elegant in presentation. Just as geometry provides fundamental truths about the universe and how it works to help shape our understanding of it, a designer’s understanding of how the basic shapes work can give subtle and substantial reinforcement to a logo to align it with its message.

p3-03-mason-symbol-opt
The geometer’s basic tools of straightedge and compass inscribed on a Masonic Hall in Lancaster, UK.

The basic geometer’s tools are as simple as the initial shapes they construct. A drawing compass, pencil and straightedge are the only tools you need to create a range of geometric possibilities.

Not only do geometric forms describe specific functions that don’t change when scaled from micro to macro sizes (for example, the containment of a circular egg to a spherical planet), the progressed order of how the shapes are constructed parallels the order of dimensional space. Zero, one, two, three and four dimensions are also known as degrees of freedom. Degrees of freedom express the progression of independence from lower to higher dimensions, beginning with the zero dimension, which corresponds with the initial geometric shape of the circle.

The Circle: Zero Dimension

Geometry begins with the center point of a compass, the source of the all-encompassing circle. The simple point is also considered a zero dimension. In physics terminology, a zero point refers to a location in space and nothing more; therefore, it has no freedoms — or a zero degree of freedom. The starting center point of a drawing compass results in the circle, which is, interestingly, a shape independent enough to continuously roll or revolve in physical space. It doesn’t have the same constraints of angled shapes that are stopped by corners (which have their purpose, too).

The encompassing circle arises from a single point and is the source of all geometric shapes.
As the primary geometer’s shape, the encompassing circle arises from a single point and is the source of all geometric shapes.

The circle is known as the mother of all shapes because it is the archetypal shape from which all other geometry is drawn. This is true in nature as well: Life begins as an absolute in the form of a single-celled egg or seed. The primary principle of the circle — a container that protects, supports and ultimately produces life — allows it to scale from minuscule organisms like cells to the mega size of our planet, which supports an immense variety of life forms.

An egg on the verge of fertilization and “Earthrise,” taken by Apollo 8 astronaut William Anders in 1968.6
An egg on the verge of fertilization and one of earth’s first selfies, “Earthrise,” taken by Apollo 8 astronaut William Anders in 1968. (Image credit: Sebastian Kaulitzki7, NASA). (View large version8)

In geometry, the circle begins as a single point that is surrounded with an infinite number of points joined as a circle. Just as a fertilized egg contains everything necessary to create any part of a living organism, the circle holds all possibilities.

In logos, a circle template implies many individuals or parts that comprise an overall whole. A circle effectively represents encompassing groups, such as collectives, non-profits, global organizations and governmental agencies.

Examples of the circular template used in logos. The Dallas Opera, the PBS™ logo and AgriCultura.9
Examples of the circular template used in logos. The Dallas Opera, PBS™ and AgriCultura. (Design: Dallas Opera/Woody Pirtle, AgriCultural/Maggie Macnab. The PBS™ logo is a registered trademark of the Public Broadcasting Service.) (View large version10)

The Dallas Opera, PBS™ and AgriCultura are examples of circular template use in logos to convey basic information about the client. The “O” of the Dallas Opera logo represents one of the two initial caps of their name and provides an encompassing template that helps to “orchestrate” a diverse collective of musicians that compose the whole of the organization. The style of the design further supports the client by referencing the grace and flow of music. The circle surrounding the PBS™ logo encompasses the diverse demographic (represented with multiple repeating heads) of a national public broadcasting company. And the hand/leaf elements representing a network of farmers that comprise the non-profit AgriCultura are included within a circular template to describe their singular purpose.

The Line: One Dimension

Just as an egg must first divide to become a multi-celled organism, the circle must be cloned to create the next geometric shape. By placing the point of a drawing compass on the outer edge of the original circle and drawing a second circle at the same diameter as the first, the original is duplicated. This presents an opportunity to connect the two center points together and “push the point” into a line, developing the point into one-dimensional space. The line can move in only one direction (forward or backward) and, therefore, has one degree of freedom. Not much happens in one-dimensional space, but it has one more degree of freedom — or one more level of independence — than the single location in space that a point occupies.

The initial cellular division of an egg that leads to new life.
The initial cellular division of an egg that leads to new life. (Image: Lawrence Livermore National Laboratory Archives)

The two circles provide another line-joining reference at their intersections. A second line connects the overlapping circles and intersects the first line drawn between center points at a 90° angle. When two opposites come into contact with one another, they establish a connection or relationship, an important consideration for some clients.

The second shape of geometry is the line, or one-dimensional space, created by connecting the two center points.11
The second shape of geometry is the line, or one-dimensional space, created by connecting the two center points. (View large version12)

In logos, elements that intersect at right angles represent opposites working together, as the visual construction describes. The power of symbolism expands this basic concept into other uses, and this configuration can be useful to represent a merger or a cooperative relationship between two primary, but different, purposes.

The basic template of intersecting lines in the Heart Hospital of New Mexico’s logo supports its purpose of treating patients who are balancing between life and death, and it complements the more specific visual communication of the design.

The Heart Hospital of New Mexico's logo.13
The Heart Hospital of New Mexico’s logo. (Design: Maggie Macnab) (View large version14)

Hospitals (and most of the Red Cross worldwide services) have historically used crossed lines as a generic icon. At a symbolic level, hospitals and emergency services are at the intersection of life (or birth) and death. I used the Zia (the symbol New Mexico uses to represent the state) and integrated a heart and hand to complete this logo concept for the Heart Hospital of New Mexico to depict the primary criteria the client wanted this logo to convey of New Mexico, cardiology and hands-on care. The specific visuals give metaphorical information to the basic template of the design (more on metaphors in part 1, “Symbols, Metaphors and the Power of Intuition”).

You can also communicate the idea of complementary opposites with the almond-shaped center of the two overlapping “mother” circles. This shape, called a mandorla or vesica piscis, is the byproduct of the geometric process that constructs a point-to-point connection.

Logo process for Swedish fish tackle company Broman Odell.15
Logo process for Swedish fish tackle company Broman Odell. (Design: Fredrik Lewander) (View large version16)

Swedish designer Fredrik Lewander used the principles of the mandorla shape to represent Broman Odell, a tackle company that joins the two business owners’ lifelong knowledge of fishing and tackle into one business. As his process shows, he worked on many options, beginning with overlapping the initial letters of their name. By expanding on this initial direction and within a simple range of concepts, he designed an elegant logo that says everything about who they are.

The Triangle: Two Dimensions

Once the point has been pushed into a line, you can take the next geometrical step by enclosing the three points as a two-dimensional triangular plane. Two degrees of freedom goes quite a bit further than one degree. The enclosed plane allows for independent motion of the x and y axis throughout its surface, rather than just the forward or backward motion of the one-dimensional line.

The third step of basic geometry encloses three points as a triangle, or two-dimensional space, which allows for freedom of movement throughout the plane.
The third step of basic geometry encloses three points as a triangle, or two-dimensional space, which allows for freedom of movement throughout the plane.

The triangle is very secure when set on its base or when combined with upside-down versions of itself in translation symmetry — which is why it is often used as a structural support in building construction or as a two-dimensional border design in artwork. This is the shape of geodesic domes, bridge trusses, arched doorways (a triangle that incorporates a curve at its top point), as well as the triangular skeletal scaffolding of the human pelvis which enables upright walking.

The shape of the triangle is a secure structural truss.17
The shape of the triangle is a secure structural truss. (View large version18)

As a shape, the triangle’s structure funnels from a solid base into a point. Philosophically, it is grounded in the here and now and points to something unseen. It’s evident why the triangle is used as an arrow: it leads the eye away from one thing and toward something else. Because of these properties, the triangle is often used to symbolize inspiration or aspiration beyond a current stasis. A mountain’s summit is an inspirational metaphor, as a common example.

The recycling symbol is a brilliant use of the triangle — and triangular arrows — to complete a complex concept as a simple icon.
The recycling symbol is a brilliant use of the triangle — and triangular arrows — to complete a complex concept as a simple icon. (Image credit: Will Smith19)

Recycling is the three-part act of coming into existence, existing, and then being folded back into the mix for another future purpose. More simply stated, the triangle is a metaphor for birth, life and death, or beginning, middle and end. The recycling symbol expresses this sequence in the simplest way possible: as triangular arrows that enclose the three parts of a triangle.

The triangle is also a symbol of transformation as the go-between of one- and three-dimensional space. All words that begin with the prefix tri- (for the three parts necessary to achieve the balance of a midpoint) or trans- (Latin for “across”) refer to the power of the triangle to secure space so that a significant change or movement can occur. Metaphorically, life begins as a zero dimension with a single-celled egg. It then divides in order to multiply at conception (as a metaphor for one dimension) and develops into a multi-celled embryo within the secure, triangular space of the pelvis (as a metaphor for two dimensions). When gestated, what was once a single-celled egg emerges into life fully formed and infinitely more complex (as a metaphor for three dimensions). Life is then lived through time, as a metaphoric reference to the fourth dimension.

The nineteenth-century calligraphic design by Japanese Zen master Sengai Gibon, entitled “Universe,” literally translates as “Circle, Triangle, Square.” The painting shows the universal process of wholeness dividing, transforming and becoming, as a symbolic process of shapes read right to left in traditional Asian style.

Calligraphic design “Universe,” literally translates as “Circle, Triangle, Square.”
Calligraphic design “Universe,” literally translates as “Circle, Triangle, Square” read right to left. (Image: Idemitsu Museum of Art, Tokyo)

The triangle has powerful associations. Incorporated into a logo, it can symbolize “looking beyond” or inspiration, a significant change (transformation) or a significant movement (transportation). Note that many automobile makers use a triangle or three elements to describe their products.

The triangle sitting at the top an unfinished pyramid in the dollar bill symbolizes the inspired hope of a new country, security and transforming the past into a better future. The three-legged symbol of the Department of Transportation’s logo references the ancient triskelion, a symbol of perpetual motion. Note that the circle template is also used here to represent an organization responsible for the mass movement of an entire country. Geometrical symbols are simple enough to be used together to instantly enhance meaning in a logo.

The triangle in the dollar bill and the Department of Transportation's logo20
The triangle in the dollar bill and the Department of Transportation’s logo. (Image credit: Instamatic21). (View large version22)

In the logo design for MuSE (Multi-User Synthetic Environment), I wanted to represent the client’s purpose of interpreting raw computer data as useful visuals. For example, a surgeon must use an MRI scan to successfully navigate the brain to remove a tumor; the program can also test various launch patterns to ensure that a missile isn’t accidentally deployed in a random occurrence such as a lightning strike.

p3-16-muse-process-opt-small23
Initial sketches and final process of the MuSE logo. (Design: Maggie Macnab) (View large version24)
Initial sketches and final process of the MuSE logo.
Initial sketches and final process of the MuSE logo. (Design: Maggie Macnab)

Mythical muses relate the visual to the name; the triangular template aligns the company’s purpose of transforming numerical data into something more; and the three parts of the face defined in shadow represent the quality of contour, or depth visualized in two dimensions.

Four-Sided Figures: Three Dimensions

Squares and rectangles are probably the least interesting of the basic geometric shapes, but they are still useful. Adding a fourth point of depth creates a tetrahedron (or a pyramid) with the z axis, bringing it into the three-dimensional realm. We use the shorthand of a four-sided shape to describe the four points of three-dimensional space (or three degrees of freedom).

The fourth point brings depth (the z axis) to the triangle, a stable shape in three dimensional space.25
The fourth point brings depth (the z axis) to the triangle, a stable shape in three dimensional space. (View large version26)

Everything about a shape with four points says stability. While not a common shape in nature, four-sided shapes make reliable human-made structures such as city grids, parks and center squares, buildings, building materials (bricks, adobes, ceiling and floor tiles), windows, monitors, and framed artwork — even paper money gets a boost to further substantiate its value through shape. (Precious metals minted in coins are a historical benchmark of value that remains relatively consistent because weight can be measured accurately. Conversely, the worth of paper money vacillates wildly because it is based in markets that can be willfully manipulated. The massive printing worldwide of paper currencies during the economic crisis of the last several years is an example of this.)

The four-sided figure exemplifies the world as manifest, solid and real. It is forthright, fortified and forward — words that connect the etymology of the number four to stability and tangibility. This shape is plain and boxy, and the logos that use it present the client in just that sort of straightforward way. Banks, attorneys, insurance and accounting companies and, of course, contractors commonly use this template to identify themselves as stable institutions or makers of reliable structures.

The MediaDesk NM logo.
The MediaDesk NM logo. (Design: Maggie Macnab)

MediaDesk NM gives non-profits access to advanced communication infrastructure services so that they can leverage mutual resources leaving more resources to contribute to their communities. Visual specifics were taken from the company’s name: media, desk and New Mexico. Desks are four-sided, and the shape of the state of New Mexico is squarish. These qualities were broken down into smaller boxes as a speech bubble tail to illustrate communication and media. The smaller squares also metaphorically represent the individual non-profits that contribute to the overall stability of the non-profits in New Mexico.

The Five-Pointed Star And Its Sister Shape, The Spiral: Four Degrees Of Freedom

Five points are the foundation of pentagons and five-pointed stars. Stars are associated with excellence: five star generals, restaurants, hotels and flag designs all come to mind, as do the celebrities who burn brightly above the rest of us as “stars.” The human body exhibits the number five in several iterations: we have five extensions that branch from our torso, five fingers on each hand to use tools, five toes on each foot to move us through space, and five primary senses. The number five is pervasive in human functionality.

The classic Vitruvian Man by Leonardo da Vinci
The classic Vitruvian Man by Leonardo da Vinci.

While I would never suggest you eat anything you don’t know to be safe, if you ever find yourself in the position of needing to source food from nature to survive (relatively speaking, this was the norm not very long ago), keep in mind that fruits produced from five-petaled blossoms (such as apricots and pears) or spiral flowering plants (such as the rose, which produces vitamin C in rose hips) are typically nutritious for the human body. In contrast, many six-petaled flowering plants are poisonous or medicinal (medicine and poison are the same thing in different proportions).

Apples, cherries, peaches, squash — all have five-petaled flowers that produce nutritious fruit for the human body.27
Apples, cherries, peaches, squash – all have five-petaled flowers that produce nutritious fruit for the human body. (Image credit: Rafal Ulicki28, www.visuallanguage.com29, CatbirdHill30) (View large version31)

When it comes to something as important as our body and the nutrition that feeds it, it is no wonder that stars represent the best of the best. Converse and Starbucks are two high-profile contemporary logos that use stars as a design element to convey their status as the very best. Stars are not one of the shapes used widely in cultural artwork, but they have a deep connection to the spiral, which is.

Stars Love Spirals And Spirals Love Stars

A star can be used as a template to create the spiral, one of the universal shapes. Multiple embedded rotations of the star’s triangular arm can be scaled to smaller and smaller sizes and their outline traced to create a spiral. This shape’s ability to rotate itself at smaller or greater scales consistently and infinitely speaks to the principle of regeneration.

The ability of a star's points to scale infinitely provides a geometric source for the spiral's construction.32
The ability of a star’s points to scale infinitely provides a geometric source for the spiral’s construction. Using curves instead of angles creates the phi spiral. (View large version33)

The spiral is a visual representation of cyclical time in space, repeating as a consistent but new cycle with each rotation. This is the fourth dimension of time and space (see the phi construction animation in part 2, “Using Nature’s Patterns in Logo Design,” for a more visceral understanding of this phenomena).

The five-pointed star and the spiral are also entwined in nature. You can see this relationship in a sunflower. From a bird’s-eye view, the five-pointed star is visible in the sequential growth of a plant’s leaves, and in profile those leaves travel around the plant’s stalk in a spiraling pattern. The two aspects work together to provide the most access to sunlight to the plant because of minimized shadows and the spiral path also funnels rainwater along the stalk, sending it to directly the roots where it does the most good.

The bird's-eye view of leaves in a five-pointed star show the pattern of leaves spiraling around the plant's stalk in profile.
The bird’s-eye view of leaves in a five-pointed star show the pattern of leaves spiraling around the plant’s stalk in profile. (Image credit: Andriy Solovyov34)

Clients involved in creative ventures and potential or futuristic visioning and thinking organizations (time figuring in here again) are good matches for the principles expressed by this shape.

Swan Songs is a non-profit collective of musicians who play requests for the dying, and I knew instantly that the treble clef could embody a swan in its shape. It was just a matter of drawing it out. The client chose an appropriate name for their organization, and I integrated qualities of the swan with the musical symbol to capture their purpose of providing musical last requests to individuals with a terminal illness.

The Swan Songs Logo35
The Swan Songs Logo. (Image credit: Eric Isselee36, Design: Maggie Macnab) (View large version37)

Besides integrating the organization’s most distinct visual qualities, the spiral shape of this logo relates to the symbol for infinity, a metaphor for the endless loop of existence that regenerates life. The logo’s message is consoling and positive to its audience — and it complements the non-profit’s purpose.

Conclusion

Who would have thought that simple geometry has such depth and relevance? It is supremely efficient when applied thoughtfully to a logo. While geometric shapes are far too broad to stand on their own as a logo design, their ability to communicate universally can support the overall message you want your design to convey. Add to that a combination of symbols, metaphors and relevant natural patterns, and your simple but elegantly crafted logo will speak volumes to your audience instantly, seamlessly and memorably.

(ml, al)

Footnotes

  1. 1 http://www.smashingmagazine.com/2015/06/12/effective-logo-design-nature-pattern/
  2. 2 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-02-5-shapes-opt.jpg
  3. 3 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-02-5-shapes-opt.jpg
  4. 4 http://www.smashingmagazine.com/2015/06/05/effective-logo-design-symbols-metaphors-intuition/
  5. 5 http://www.smashingmagazine.com/2015/06/12/effective-logo-design-nature-pattern/
  6. 6 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-05-circle-nature-opt.jpg
  7. 7 http://www.shutterstock.com/g/eraxion
  8. 8 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-05-circle-nature-opt.jpg
  9. 9 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-06-circle-logos-opt.jpg
  10. 10 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-06-circle-logos-opt.jpg
  11. 11 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-08-line-opt.jpg
  12. 12 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-08-line-opt.jpg
  13. 13 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-09-hhnm-opt.jpg
  14. 14 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-09-hhnm-opt.jpg
  15. 15 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-10-bromanodell-process-opt.jpg
  16. 16 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-10-bromanodell-process-opt.jpg
  17. 17 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-12-bridge-truss-opt.jpg
  18. 18 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-12-bridge-truss-opt.jpg
  19. 19 http://www.mayang.com
  20. 20 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-15-money-triskelion-opt.jpg
  21. 21 http://www.shutterstock.com/ru/s/instamatic/search.html
  22. 22 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-15-money-triskelion-opt.jpg
  23. 23 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-16-muse-process-opt.jpg
  24. 24 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-16-muse-process-opt.jpg
  25. 25 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-18-tetrahedron-opt.jpg
  26. 26 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-18-tetrahedron-opt.jpg
  27. 27 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-21-5-petals-opt.jpg
  28. 28 http://www.shutterstock.com/g/rafalulicki
  29. 29 http://www.visuallanguage.com
  30. 30 http://www.shutterstock.com/g/CatbirdHill
  31. 31 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-21-5-petals-opt.jpg
  32. 32 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-22-star-spiral-opt.jpg
  33. 33 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-22-star-spiral-opt.jpg
  34. 34 http://www.shutterstock.com/g/mastermag08
  35. 35 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-24-swansongs-process-opt.jpg
  36. 36 http://www.shutterstock.com/g/isselee
  37. 37 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-24-swansongs-process-opt.jpg

The post Effective Logo Design, Part 3: How Geometry Influences Logo Design appeared first on Smashing Magazine.

Categories: Others Tags:

Effective Logo Design, Part 3: How Geometry Influences Logo Design

June 23rd, 2015 No comments
The five basic geometric shapes used in all cultural artwork in order of least to most complex

Galileo knew it. Every ancient culture that left traces of knowledge in their art knew it. Basic shapes compose the fundamental geometry of the universe. We can take credit for a lot of things, but human beings did not invent geometric shapes. We discovered them through the observation of nature1. Understanding basic shapes and their functions have taught us to mark time and space in a variety of ways inspiring mathematics, technology, language and ever-evolving civilization.

“The universe cannot be read until we learn the language in which it is written. It is written in mathematics, and the letters are triangles, circles and other geometrical figures, without which it is humanly impossible to understand a single word.”

– Galileo Galilei

A handful of simple shapes have been used throughout time in the art of all cultures: the circle, intersecting lines, the triangle, the square and the spiral. Cultural anthropologist Angeles Arrien researched and documented commonalities in cultural art forms over several decades and found consistent geometric shapes embedded in all art. She called them the “five universal shapes.”

2
The five basic geometric shapes used in all cultural artwork in order of least to most complex. (View large version3)

Each fundamental shape never varies in its basic function because each unifies purpose with form. A circle rolls freely, lines travel and intersect, a triangle sits securely while pointing away from itself, a four-sided shape is imminently stable, and a spiral curls with elegant persistence. Don’t let the simplicity of these forms fool you. It is because they are so simple that they have the ability to scale consistently and are used as the building blocks of nature and the man-made world. They also provide consistent messaging for a logo.

This three-part series explores fundamental creative strategies for designing effective logos. The first part4 shows how to use symbols, metaphors and the power of intuition. The second part5 shows how to use nature’s patterns in logo design. This last part is about how geometry influences logo design.

A Little Geometry (Goes A Long Way)

The purpose of a logo is to communicate the client in the simplest but most comprehensive way possible. The basic shapes communicate fundamental qualities of the organization in the most immediate way and they are used in design of every ilk — graphic, environmental, interior, product and industrial design, and architecture.

To understand the connections between form and function in each geometric shape, I’ll give an overview of how it is created, how it sets the stage for the next shape, how it appears in nature and the built world, and the kinds of clients it would be a good fit for. The shapes begin simply but become complex as they are developed, just as our experience of living does over time. They are also related to the spatial dimensions we experience through the process of living.

“To me no experience of childhood so reinforced self-confidence in one’s own exploratory faculties as did geometry.”

– Buckminster Fuller

Our senses are responsible for processing an incredible amount of information every moment of every day. Only a small fraction of that information makes it into consciousness because the brain simply can’t process the endless stream generated by the outside world. Because of the sheer quantity of it, most of our experience is absorbed subliminally.

Digital technology has removed much of the tactile experience in just a few decades. But touch has been an important part of how we have understood the world throughout our entire history. Using traditional drawing tools keeps us rooted in the tangible world. So, now and then, be hands-on to get a more comprehensive understanding of what you are creating. Draw, spend time in nature without an agenda, and experiment with geometry by hand so that your design is multifaceted in meaning but elegant in presentation. Just as geometry provides fundamental truths about the universe and how it works to help shape our understanding of it, a designer’s understanding of how the basic shapes work can give subtle and substantial reinforcement to a logo to align it with its message.

p3-03-mason-symbol-opt
The geometer’s basic tools of straightedge and compass inscribed on a Masonic Hall in Lancaster, UK.

The basic geometer’s tools are as simple as the initial shapes they construct. A drawing compass, pencil and straightedge are the only tools you need to create a range of geometric possibilities.

Not only do geometric forms describe specific functions that don’t change when scaled from micro to macro sizes (for example, the containment of a circular egg to a spherical planet), the progressed order of how the shapes are constructed parallels the order of dimensional space. Zero, one, two, three and four dimensions are also known as degrees of freedom. Degrees of freedom express the progression of independence from lower to higher dimensions, beginning with the zero dimension, which corresponds with the initial geometric shape of the circle.

The Circle: Zero Dimension

Geometry begins with the center point of a compass, the source of the all-encompassing circle. The simple point is also considered a zero dimension. In physics terminology, a zero point refers to a location in space and nothing more; therefore, it has no freedoms — or a zero degree of freedom. The starting center point of a drawing compass results in the circle, which is, interestingly, a shape independent enough to continuously roll or revolve in physical space. It doesn’t have the same constraints of angled shapes that are stopped by corners (which have their purpose, too).

The encompassing circle arises from a single point and is the source of all geometric shapes.
As the primary geometer’s shape, the encompassing circle arises from a single point and is the source of all geometric shapes.

The circle is known as the mother of all shapes because it is the archetypal shape from which all other geometry is drawn. This is true in nature as well: Life begins as an absolute in the form of a single-celled egg or seed. The primary principle of the circle — a container that protects, supports and ultimately produces life — allows it to scale from minuscule organisms like cells to the mega size of our planet, which supports an immense variety of life forms.

An egg on the verge of fertilization and “Earthrise,” taken by Apollo 8 astronaut William Anders in 1968.6
An egg on the verge of fertilization and one of earth’s first selfies, “Earthrise,” taken by Apollo 8 astronaut William Anders in 1968. (Image credit: Sebastian Kaulitzki7, NASA). (View large version8)

In geometry, the circle begins as a single point that is surrounded with an infinite number of points joined as a circle. Just as a fertilized egg contains everything necessary to create any part of a living organism, the circle holds all possibilities.

In logos, a circle template implies many individuals or parts that comprise an overall whole. A circle effectively represents encompassing groups, such as collectives, non-profits, global organizations and governmental agencies.

Examples of the circular template used in logos. The Dallas Opera, the PBS™ logo and AgriCultura.9
Examples of the circular template used in logos. The Dallas Opera, PBS™ and AgriCultura. (Design: Dallas Opera/Woody Pirtle, AgriCultural/Maggie Macnab. The PBS™ logo is a registered trademark of the Public Broadcasting Service.) (View large version10)

The Dallas Opera, PBS™ and AgriCultura are examples of circular template use in logos to convey basic information about the client. The “O” of the Dallas Opera logo represents one of the two initial caps of their name and provides an encompassing template that helps to “orchestrate” a diverse collective of musicians that compose the whole of the organization. The style of the design further supports the client by referencing the grace and flow of music. The circle surrounding the PBS™ logo encompasses the diverse demographic (represented with multiple repeating heads) of a national public broadcasting company. And the hand/leaf elements representing a network of farmers that comprise the non-profit AgriCultura are included within a circular template to describe their singular purpose.

The Line: One Dimension

Just as an egg must first divide to become a multi-celled organism, the circle must be cloned to create the next geometric shape. By placing the point of a drawing compass on the outer edge of the original circle and drawing a second circle at the same diameter as the first, the original is duplicated. This presents an opportunity to connect the two center points together and “push the point” into a line, developing the point into one-dimensional space. The line can move in only one direction (forward or backward) and, therefore, has one degree of freedom. Not much happens in one-dimensional space, but it has one more degree of freedom — or one more level of independence — than the single location in space that a point occupies.

The initial cellular division of an egg that leads to new life.
The initial cellular division of an egg that leads to new life. (Image: Lawrence Livermore National Laboratory Archives)

The two circles provide another line-joining reference at their intersections. A second line connects the overlapping circles and intersects the first line drawn between center points at a 90° angle. When two opposites come into contact with one another, they establish a connection or relationship, an important consideration for some clients.

The second shape of geometry is the line, or one-dimensional space, created by connecting the two center points.11
The second shape of geometry is the line, or one-dimensional space, created by connecting the two center points. (View large version12)

In logos, elements that intersect at right angles represent opposites working together, as the visual construction describes. The power of symbolism expands this basic concept into other uses, and this configuration can be useful to represent a merger or a cooperative relationship between two primary, but different, purposes.

The basic template of intersecting lines in the Heart Hospital of New Mexico’s logo supports its purpose of treating patients who are balancing between life and death, and it complements the more specific visual communication of the design.

The Heart Hospital of New Mexico's logo.13
The Heart Hospital of New Mexico’s logo. (Design: Maggie Macnab) (View large version14)

Hospitals (and most of the Red Cross worldwide services) have historically used crossed lines as a generic icon. At a symbolic level, hospitals and emergency services are at the intersection of life (or birth) and death. I used the Zia (the symbol New Mexico uses to represent the state) and integrated a heart and hand to complete this logo concept for the Heart Hospital of New Mexico to depict the primary criteria the client wanted this logo to convey of New Mexico, cardiology and hands-on care. The specific visuals give metaphorical information to the basic template of the design (more on metaphors in part 1, “Symbols, Metaphors and the Power of Intuition”).

You can also communicate the idea of complementary opposites with the almond-shaped center of the two overlapping “mother” circles. This shape, called a mandorla or vesica piscis, is the byproduct of the geometric process that constructs a point-to-point connection.

Logo process for Swedish fish tackle company Broman Odell.15
Logo process for Swedish fish tackle company Broman Odell. (Design: Fredrik Lewander) (View large version16)

Swedish designer Fredrik Lewander used the principles of the mandorla shape to represent Broman Odell, a tackle company that joins the two business owners’ lifelong knowledge of fishing and tackle into one business. As his process shows, he worked on many options, beginning with overlapping the initial letters of their name. By expanding on this initial direction and within a simple range of concepts, he designed an elegant logo that says everything about who they are.

The Triangle: Two Dimensions

Once the point has been pushed into a line, you can take the next geometrical step by enclosing the three points as a two-dimensional triangular plane. Two degrees of freedom goes quite a bit further than one degree. The enclosed plane allows for independent motion of the x and y axis throughout its surface, rather than just the forward or backward motion of the one-dimensional line.

The third step of basic geometry encloses three points as a triangle, or two-dimensional space, which allows for freedom of movement throughout the plane.
The third step of basic geometry encloses three points as a triangle, or two-dimensional space, which allows for freedom of movement throughout the plane.

The triangle is very secure when set on its base or when combined with upside-down versions of itself in translation symmetry — which is why it is often used as a structural support in building construction or as a two-dimensional border design in artwork. This is the shape of geodesic domes, bridge trusses, arched doorways (a triangle that incorporates a curve at its top point), as well as the triangular skeletal scaffolding of the human pelvis which enables upright walking.

The shape of the triangle is a secure structural truss.17
The shape of the triangle is a secure structural truss. (View large version18)

As a shape, the triangle’s structure funnels from a solid base into a point. Philosophically, it is grounded in the here and now and points to something unseen. It’s evident why the triangle is used as an arrow: it leads the eye away from one thing and toward something else. Because of these properties, the triangle is often used to symbolize inspiration or aspiration beyond a current stasis. A mountain’s summit is an inspirational metaphor, as a common example.

The recycling symbol is a brilliant use of the triangle — and triangular arrows — to complete a complex concept as a simple icon.
The recycling symbol is a brilliant use of the triangle — and triangular arrows — to complete a complex concept as a simple icon. (Image credit: Will Smith19)

Recycling is the three-part act of coming into existence, existing, and then being folded back into the mix for another future purpose. More simply stated, the triangle is a metaphor for birth, life and death, or beginning, middle and end. The recycling symbol expresses this sequence in the simplest way possible: as triangular arrows that enclose the three parts of a triangle.

The triangle is also a symbol of transformation as the go-between of one- and three-dimensional space. All words that begin with the prefix tri- (for the three parts necessary to achieve the balance of a midpoint) or trans- (Latin for “across”) refer to the power of the triangle to secure space so that a significant change or movement can occur. Metaphorically, life begins as a zero dimension with a single-celled egg. It then divides in order to multiply at conception (as a metaphor for one dimension) and develops into a multi-celled embryo within the secure, triangular space of the pelvis (as a metaphor for two dimensions). When gestated, what was once a single-celled egg emerges into life fully formed and infinitely more complex (as a metaphor for three dimensions). Life is then lived through time, as a metaphoric reference to the fourth dimension.

The nineteenth-century calligraphic design by Japanese Zen master Sengai Gibon, entitled “Universe,” literally translates as “Circle, Triangle, Square.” The painting shows the universal process of wholeness dividing, transforming and becoming, as a symbolic process of shapes read right to left in traditional Asian style.

Calligraphic design “Universe,” literally translates as “Circle, Triangle, Square.”
Calligraphic design “Universe,” literally translates as “Circle, Triangle, Square” read right to left. (Image: Idemitsu Museum of Art, Tokyo)

The triangle has powerful associations. Incorporated into a logo, it can symbolize “looking beyond” or inspiration, a significant change (transformation) or a significant movement (transportation). Note that many automobile makers use a triangle or three elements to describe their products.

The triangle sitting at the top an unfinished pyramid in the dollar bill symbolizes the inspired hope of a new country, security and transforming the past into a better future. The three-legged symbol of the Department of Transportation’s logo references the ancient triskelion, a symbol of perpetual motion. Note that the circle template is also used here to represent an organization responsible for the mass movement of an entire country. Geometrical symbols are simple enough to be used together to instantly enhance meaning in a logo.

The triangle in the dollar bill and the Department of Transportation's logo20
The triangle in the dollar bill and the Department of Transportation’s logo. (Image credit: Instamatic21). (View large version22)

In the logo design for MuSE (Multi-User Synthetic Environment), I wanted to represent the client’s purpose of interpreting raw computer data as useful visuals. For example, a surgeon must use an MRI scan to successfully navigate the brain to remove a tumor; the program can also test various launch patterns to ensure that a missile isn’t accidentally deployed in a random occurrence such as a lightning strike.

p3-16-muse-process-opt-small23
Initial sketches and final process of the MuSE logo. (Design: Maggie Macnab) (View large version24)
Initial sketches and final process of the MuSE logo.
Initial sketches and final process of the MuSE logo. (Design: Maggie Macnab)

Mythical muses relate the visual to the name; the triangular template aligns the company’s purpose of transforming numerical data into something more; and the three parts of the face defined in shadow represent the quality of contour, or depth visualized in two dimensions.

Four-Sided Figures: Three Dimensions

Squares and rectangles are probably the least interesting of the basic geometric shapes, but they are still useful. Adding a fourth point of depth creates a tetrahedron (or a pyramid) with the z axis, bringing it into the three-dimensional realm. We use the shorthand of a four-sided shape to describe the four points of three-dimensional space (or three degrees of freedom).

The fourth point brings depth (the z axis) to the triangle, a stable shape in three dimensional space.25
The fourth point brings depth (the z axis) to the triangle, a stable shape in three dimensional space. (View large version26)

Everything about a shape with four points says stability. While not a common shape in nature, four-sided shapes make reliable human-made structures such as city grids, parks and center squares, buildings, building materials (bricks, adobes, ceiling and floor tiles), windows, monitors, and framed artwork — even paper money gets a boost to further substantiate its value through shape. (Precious metals minted in coins are a historical benchmark of value that remains relatively consistent because weight can be measured accurately. Conversely, the worth of paper money vacillates wildly because it is based in markets that can be willfully manipulated. The massive printing worldwide of paper currencies during the economic crisis of the last several years is an example of this.)

The four-sided figure exemplifies the world as manifest, solid and real. It is forthright, fortified and forward — words that connect the etymology of the number four to stability and tangibility. This shape is plain and boxy, and the logos that use it present the client in just that sort of straightforward way. Banks, attorneys, insurance and accounting companies and, of course, contractors commonly use this template to identify themselves as stable institutions or makers of reliable structures.

The MediaDesk NM logo.
The MediaDesk NM logo. (Design: Maggie Macnab)

MediaDesk NM gives non-profits access to advanced communication infrastructure services so that they can leverage mutual resources leaving more resources to contribute to their communities. Visual specifics were taken from the company’s name: media, desk and New Mexico. Desks are four-sided, and the shape of the state of New Mexico is squarish. These qualities were broken down into smaller boxes as a speech bubble tail to illustrate communication and media. The smaller squares also metaphorically represent the individual non-profits that contribute to the overall stability of the non-profits in New Mexico.

The Five-Pointed Star And Its Sister Shape, The Spiral: Four Degrees Of Freedom

Five points are the foundation of pentagons and five-pointed stars. Stars are associated with excellence: five star generals, restaurants, hotels and flag designs all come to mind, as do the celebrities who burn brightly above the rest of us as “stars.” The human body exhibits the number five in several iterations: we have five extensions that branch from our torso, five fingers on each hand to use tools, five toes on each foot to move us through space, and five primary senses. The number five is pervasive in human functionality.

The classic Vitruvian Man by Leonardo da Vinci
The classic Vitruvian Man by Leonardo da Vinci.

While I would never suggest you eat anything you don’t know to be safe, if you ever find yourself in the position of needing to source food from nature to survive (relatively speaking, this was the norm not very long ago), keep in mind that fruits produced from five-petaled blossoms (such as apricots and pears) or spiral flowering plants (such as the rose, which produces vitamin C in rose hips) are typically nutritious for the human body. In contrast, many six-petaled flowering plants are poisonous or medicinal (medicine and poison are the same thing in different proportions).

Apples, cherries, peaches, squash — all have five-petaled flowers that produce nutritious fruit for the human body.27
Apples, cherries, peaches, squash – all have five-petaled flowers that produce nutritious fruit for the human body. (Image credit: Rafal Ulicki28, www.visuallanguage.com29, CatbirdHill30) (View large version31)

When it comes to something as important as our body and the nutrition that feeds it, it is no wonder that stars represent the best of the best. Converse and Starbucks are two high-profile contemporary logos that use stars as a design element to convey their status as the very best. Stars are not one of the shapes used widely in cultural artwork, but they have a deep connection to the spiral, which is.

Stars Love Spirals And Spirals Love Stars

A star can be used as a template to create the spiral, one of the universal shapes. Multiple embedded rotations of the star’s triangular arm can be scaled to smaller and smaller sizes and their outline traced to create a spiral. This shape’s ability to rotate itself at smaller or greater scales consistently and infinitely speaks to the principle of regeneration.

The ability of a star's points to scale infinitely provides a geometric source for the spiral's construction.32
The ability of a star’s points to scale infinitely provides a geometric source for the spiral’s construction. Using curves instead of angles creates the phi spiral. (View large version33)

The spiral is a visual representation of cyclical time in space, repeating as a consistent but new cycle with each rotation. This is the fourth dimension of time and space (see the phi construction animation in part 2, “Using Nature’s Patterns in Logo Design,” for a more visceral understanding of this phenomena).

The five-pointed star and the spiral are also entwined in nature. You can see this relationship in a sunflower. From a bird’s-eye view, the five-pointed star is visible in the sequential growth of a plant’s leaves, and in profile those leaves travel around the plant’s stalk in a spiraling pattern. The two aspects work together to provide the most access to sunlight to the plant because of minimized shadows and the spiral path also funnels rainwater along the stalk, sending it to directly the roots where it does the most good.

The bird's-eye view of leaves in a five-pointed star show the pattern of leaves spiraling around the plant's stalk in profile.
The bird’s-eye view of leaves in a five-pointed star show the pattern of leaves spiraling around the plant’s stalk in profile. (Image credit: Andriy Solovyov34)

Clients involved in creative ventures and potential or futuristic visioning and thinking organizations (time figuring in here again) are good matches for the principles expressed by this shape.

Swan Songs is a non-profit collective of musicians who play requests for the dying, and I knew instantly that the treble clef could embody a swan in its shape. It was just a matter of drawing it out. The client chose an appropriate name for their organization, and I integrated qualities of the swan with the musical symbol to capture their purpose of providing musical last requests to individuals with a terminal illness.

The Swan Songs Logo35
The Swan Songs Logo. (Image credit: Eric Isselee36, Design: Maggie Macnab) (View large version37)

Besides integrating the organization’s most distinct visual qualities, the spiral shape of this logo relates to the symbol for infinity, a metaphor for the endless loop of existence that regenerates life. The logo’s message is consoling and positive to its audience — and it complements the non-profit’s purpose.

Conclusion

Who would have thought that simple geometry has such depth and relevance? It is supremely efficient when applied thoughtfully to a logo. While geometric shapes are far too broad to stand on their own as a logo design, their ability to communicate universally can support the overall message you want your design to convey. Add to that a combination of symbols, metaphors and relevant natural patterns, and your simple but elegantly crafted logo will speak volumes to your audience instantly, seamlessly and memorably.

(ml, al)

Footnotes

  1. 1 http://www.smashingmagazine.com/2015/06/12/effective-logo-design-nature-pattern/
  2. 2 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-02-5-shapes-opt.jpg
  3. 3 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-02-5-shapes-opt.jpg
  4. 4 http://www.smashingmagazine.com/2015/06/05/effective-logo-design-symbols-metaphors-intuition/
  5. 5 http://www.smashingmagazine.com/2015/06/12/effective-logo-design-nature-pattern/
  6. 6 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-05-circle-nature-opt.jpg
  7. 7 http://www.shutterstock.com/g/eraxion
  8. 8 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-05-circle-nature-opt.jpg
  9. 9 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-06-circle-logos-opt.jpg
  10. 10 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-06-circle-logos-opt.jpg
  11. 11 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-08-line-opt.jpg
  12. 12 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-08-line-opt.jpg
  13. 13 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-09-hhnm-opt.jpg
  14. 14 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-09-hhnm-opt.jpg
  15. 15 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-10-bromanodell-process-opt.jpg
  16. 16 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-10-bromanodell-process-opt.jpg
  17. 17 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-12-bridge-truss-opt.jpg
  18. 18 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-12-bridge-truss-opt.jpg
  19. 19 http://www.mayang.com
  20. 20 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-15-money-triskelion-opt.jpg
  21. 21 http://www.shutterstock.com/ru/s/instamatic/search.html
  22. 22 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-15-money-triskelion-opt.jpg
  23. 23 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-16-muse-process-opt.jpg
  24. 24 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-16-muse-process-opt.jpg
  25. 25 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-18-tetrahedron-opt.jpg
  26. 26 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-18-tetrahedron-opt.jpg
  27. 27 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-21-5-petals-opt.jpg
  28. 28 http://www.shutterstock.com/g/rafalulicki
  29. 29 http://www.visuallanguage.com
  30. 30 http://www.shutterstock.com/g/CatbirdHill
  31. 31 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-21-5-petals-opt.jpg
  32. 32 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-22-star-spiral-opt.jpg
  33. 33 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-22-star-spiral-opt.jpg
  34. 34 http://www.shutterstock.com/g/mastermag08
  35. 35 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-24-swansongs-process-opt.jpg
  36. 36 http://www.shutterstock.com/g/isselee
  37. 37 http://www.smashingmagazine.com/wp-content/uploads/2015/06/p3-24-swansongs-process-opt.jpg

The post Effective Logo Design, Part 3: How Geometry Influences Logo Design appeared first on Smashing Magazine.

Categories: Others Tags:

Why we Made Vorlon.js and How to Use it to Debug Your JavaScript Remotely

June 23rd, 2015 No comments

Recently at //BUILD/ 2015 we announced vorlon.js – an open source, extensible, platform-agnostic tool for remotely debugging and testing your JavaScript. I had the opportunity to create vorlon.JS with the help of some talented engineers and tech evangelists at Microsoft (the same guys that brought you http://www.babylonjs.com/). Vorlon.js is powered by node.JS, socket.io, and late-night coffee. I would like to share with you why we made it, how to incorporate it into your own testing workflow, and also share some more details into the art of building a JS library like it. Why Vorlon.js? Vorlon.js helps you remotely load, inspect, test and debug JavaScript code running on any device with a web browser. Whether it is a game console, mobile device, or even an IoT- connected refrigerator, you can remotely connect up to 50 devices and execute JavaScript in each or all of them. The idea here is that dev teams can also debug together – each person can write code and the results are visible to all. We had a simple motto in this project: No native code, no dependency to a specific browser, only JavaScript, HTML and CSS running on the devices of your choice. Vorlon.js itself is […]

Categories: Others Tags:

Qualities Of Good Flux Implementations

June 22nd, 2015 No comments
Unidirectional data flow in lux.js

It has been an exciting year for my team. Last year we kicked off a project using React31, and over the course of the project we’ve learned a lot about React and Flux2 — Facebook’s recommended architectural principles for React apps. In this article, we’ll take a look at some of the key lessons we’ve learned.

Whether you’re new to React and Flux, or going as far as building your own Flux implementation, I think you’ll not only enjoy this journey with us, but find some thought-provoking questions and wisdom you can apply in your own endeavors.

Helpful Background

This post assumes you have some level of familiarity with React and Flux. Already familiar with them? Feel free to skip to “Introducing Lux.js” section. Otherwise, I recommend reading through the links below.

React

React31 is an open-source JavaScript library, maintained mainly by Facebook, and intended to be used in large applications that use data that changes over time. Obviously this is especially helpful when developing single-page applications. If you’re familiar with the model-view-controller pattern, React is considered to be only the view, handling the user interface in an app, and can be used in conjunction with other JavaScript libraries or larger MVC frameworks. Here’s a high level summary of React:

  • React focuses on view concerns, and does not attempt to be an “everything framework”
  • React UIs are built out of components.
  • React components can be written using JSX4 — an XML-based extension to JavaScript — or with plain JavaScript.
  • React components render to a virtual DOM. Subsequent renders are “diffed” with the previous render, and the minimum number of DOM mutations are executed to effectively patch the DOM to bring it up to date.

Check out Facebook’s Getting Started5 guide.

Flux

Flux6 is an architectural pattern recommended by Facebook for building apps with React. Whereas React’s opinions nudge you towards unidirectional data flow, Flux provides a fuller picture as to what that actually looks like. Several Flux implementations have arisen (LeanKit’s lux.js7, included), providing a fascinating insight into how different teams are tackling the challenges they face. A high-level summary of Flux would include:

  • Flux apps have three main abstractions: views (React components), stores, and the dispatcher.
  • Views “propagate” actions (e.g. user interaction) through the dispatcher.
  • The dispatcher handles notifying the various stores of the action.
  • If a store’s state changes, it emits a change event, and views depending on that store for state will rerender.

Check out Facebook’s overview of Flux8.

Introducing Lux.js

JavaScript developers crank out new frameworks as fast as a politician making promises at a campaign rally. Why, then, write another framework? I love this subject, though it falls outside the scope of this article. Lux.js9 is an implementation of the Flux architecture using React; we’ve tailored it to fit our team’s specific set of needs, skills and goals. In fact, our work with lux attempts to strike a delicate balance between consistent opinions and flexibility to include other libraries that best solve the problem at hand.

Over time, failing and succeeding in quite a few projects, we’ve found the following qualities to be the drivers of success in our own flux implementation:

  1. Don’t get in React’s way.
  2. Continuously eliminate boilerplate.
  3. Treat every input as an action.
  4. Store operations must be synchronous.
  5. Make it easy to play well with non-lux/non-React instances.

Examples

Dmitri Voronianski created flux-comparison10, which lets you see a side-by-side comparison of several flux variants (using a basic shopping cart example). I’ve implemented the same example using lux to help illustrate the explanations along the way. I highly recommend checking this project out — it’s a great way to quickly familiarize yourself with several leading Flux implementations.

OK, with all that out of the way, let’s look closer at the qualities I mentioned above.

Staying Out Of The Way

React does a great job at focusing only on what it aims to solve. By not being prescriptive on broader things like remote data communications (HTTP, WebSockets), and by providing hooks that enable you to incorporate non-React UI libraries, React gives you the opportunity to assemble the tools that best address the needs of your app. Just as React stays out of the way of concerns it doesn’t solve for, we’ve found it’s equally important to stay out of React’s way. It’s easy to get in the way as you begin abstracting common patterns in how you use another library/framework behind your own API. (Note: this isn’t always a bad thing!) For example, let’s look at the common component behaviors we’ve built into lux, and how our usage of them has evolved.

Controller Views

You will often hear React developers refer to controller views — a React component that typically sits at or near the top of a section of the page, which listens to one or more stores for changes in their state. As stores emit change events, the controller view updates with the new state and passes changes down to its children via props.

lux provides a controllerView method that gives you back a React component capable of listening to lux stores. Under the hood, lux uses mixins to give the React components different behaviors, and the controllerView method gives a component both a store mixin (making it capable of listening to stores), and an ActionCreator mixin (making it capable of publishing actions). For example:

var CartContainer = lux.controllerView({

  getActions: [ "cartCheckout" ],

  stores: {
    listenTo: [ "cart" ],
    onChange: function() {
      this.setState(getStateFromStores());
    }
  },

  getInitialState: function () {
    return getStateFromStores();
  },

  onCheckoutClicked: function () {
    var products = this.state.products;
    if (!products.length) {
      return;
    }
    this.cartCheckout(products);
  },

  render: function () {
    return (
      <Cart products={this.state.products} total={this.state.total} onCheckoutClicked={this.onCheckoutClicked} />
    );
  }
});

While we still like this convenient approach, we’ve found ourselves moving to the alternative approach of setting up a plain React component, and passing the lux mixins necessary to achieve the same result. Note that here we’re calling React.createClass and using the mixins option:

var CartContainer = React.createClass({

  mixins: [ lux.reactMixin.store, lux.reactMixin.actionCreator ],

  getActions: [ "cartCheckout" ],

  stores: {
    listenTo: [ "cart" ],
    onChange: function() {
      this.setState(getStateFromStores());
    }
  },

  // other methods, etc.
});

Either approach is valid, though we feel the second approach is more out of React’s way. Why?

  • We get a component’s displayName for free (as the JSX transformer will use our var name when it sees React.createClass).
  • Some controller views don’t need to be ActionCreators. The second approach means we could only pass the store mixin in those cases, keeping concerns focused. The first approach always gives the component both mixins, even if not used.
  • There’s no need to explicitly pass the React instance to lux (done via lux.initReact( React )) so that it knows how to create components.

Note: Why spend time explaining these two different approaches? It’s about staying out of React’s way. We can easily fall prey to either over- or underabstracting, thus we need to give ourselves room to adapt as our understanding improves. The evolution of our approach over time has been informed as we’ve asked ourselves what makes a good flux implementation. This process of continually questioning and evaluating is a vital part of the life of any library or framework.

Boilerplate Elimination

In our experience, adopting React and Flux has moved infrastructure and framework concerns into the background so we can focus on actually creating features for our app. Still, there are annoying bits of code that tend to crop up a lot. For example, consider this common approach to wiring/unwiring components to listen to store change events:

// Taken from the facebook-flux example:
// https://github.com/voronianski/flux-comparison/blob/master/facebook-flux/js/components/CartContainer.jsx
var CartContainer = React.createClass({
  // only showing the methods we're interested in

  componentDidMount: function () {
    CartStore.addChangeListener(this._onChange);
  },

  componentWillUnmount: function () {
    CartStore.removeChangeListener(this._onChange);
  },

  // more methods, etc.
});

Honestly, the boilerplate tax isn’t high here, but it’s still present. Since mixins can provide component life cycle methods, we made this automatic when you include lux mixins:

var ProductsListContainer = React.createClass({

  mixins: [ lux.reactMixin.store ],

  stores: {
    listenTo: [ "products" ],
    onChange: function() {
      this.setState(getAllProducts());
    }
  },

  // more methods, etc.
});

When our ProductsListContainer stands up, it will be ready to listen to any of the store namespaces provided in the stores.listenTo array, and those subscriptions will be removed if the component unmounts. Goodbye boilerplate!

ActionCreator Boilerplate

In Flux apps, you’ll usually see dedicated ActionCreator modules like this:

// snippet from: https://github.com/voronianski/flux-comparison/blob/master/facebook-flux/js/actions/ActionCreators.js
var ActionsCreators = exports;

ActionsCreators.receiveProducts = function (products) {
  AppDispatcher.handleServerAction({
    type: ActionTypes.RECEIVE_PRODUCTS,
    products: products
  });
};

ActionsCreators.addToCart = function (product) {
  AppDispatcher.handleViewAction({
    type: ActionTypes.ADD_TO_CART,
    product: product
  });
};

As we regularly asked what repeated code we could eliminate and replace with convention, ActionCreator APIs kept coming up. In our case, we use postal.js11 for communication between ActionCreators and the dispatcher (postal is an in-memory message bus library, providing advanced publish/subscribe functionality). 99.9% of the time, an ActionCreator method published an action message with no additional behavior. Things evolved over time like this:

// The very early days
// `actionChannel` is a ref to a postal channel dedicated to lux Actions
var ActionCreators = {
  addToCart: function() {
    actionChannel.publish( {
      topic: "execute.addToCart",
      data: {
        actionType: ActionTypes.ADD_TO_CART,
        actionArgs: arguments
      }
    } );
  }
};

That was very quickly abstracted into an ActionCreator mixin to enable this:

// The early-ish days
var ActionCreators = lux.actionCreator({
  addToCart: function( product ) {
    this.publishAction( ActionTypes.ADD_TO_CART, product );
  }
});

You’ll notice two things in the code above: first, the use of lux.actionCreator, which mixes lux.mixin.actionCreator into the target; and second, the publishAction method (provided by the mixin).

At the same time we were using the above mixin approach, we’d fallen into the practice of having matching handler names on our stores (the handler method name matched the action type). For example, here’s a lux store that handles the addToCart action:

var ProductStore = new lux.Store( {

  state: { products: [] },

  namespace: "products",

  handlers: {
    addToCart: function( product ) {
      var prod = this.getState().products.find( function( p ) {
          return p.id === product.id;
      } );
      prod.inventory = prod.inventory > 0 ? prod.inventory - 1 : 0;
    }
  },

  // other methods, etc.
} );

Matching action type names and store handler names made conventional wire-up very simple, but we saw another area where we could eliminate boilerplate: if 99% of our ActionCreator API implementations just published a message, why not infer creation of ActionCreator APIs based on what gets handled by stores? So we did, while still allowing custom implementations of ActionCreator methods where needed. For example, when the store instance in the snippet above is created, lux will see that it handles an addToCart action. If an ActionCreator API hasn’t already been defined for this action under lux.actions, lux will create one, with the default behavior of publishing the action message.

Taking this approach means our components can specify what ActionCreator methods they want in an à-la-carte style. In this next snippet, our ProductItemContainer is using the lux.reactMixin.actionCreator mixin, which looks for a getActions array, and provides the specified actions as top level methods on the component. You can see we’re using the addToCart ActionCreator method in the onAddToCartClicked handler method.

var ProductItemContainer = React.createClass({

  mixins: [ lux.reactMixin.actionCreator ],

  getActions: [ "addToCart" ],

  onAddToCartClicked: function () {
    this.addToCart(this.props.product);
  },

  render: function () {
    return (
      <ProductItem product={this.props.product} onAddToCartClicked={this.onAddToCartClicked} />
    );
  }
});

As with any convention, there are trade-offs. Composition is an important aspect of ActionCreator APIs. They should be modeled separate from the component(s) that use them. So far, we believe this approach upholds that, while trading some of the explicit nature (e.g. keeping ActionCreators in their own module) for flexibility and terseness.

Everything Is An Action

Since this behavior of providing ActionCreator APIs was abstracted into a mixin, it made it possible for both React components as well as non-lux/React instances to use the mixin. My team has been taking advantage of this when it comes to things like remote data APIs. We’re using a hypermedia client called halon12, which understands how to consume our hypermedia resources using an extended version of HAL13 (Hypermedia Application Language, an open specification for defining the structure of HTTP resources). Covering hypermedia is beyond the scope of this article, but a number of good14resources15exist16 if you’re interested in learning more. Our client-side wrapper for halon uses lux’s actionCreator and actionListener mixins so that it can not only publish actions, but also handle them.

We approach it this way because we believe every input — whether it be user input or queued asynchronous execution (via Ajax, postMessage, WebSockets, etc.) — should be fed into the client as an action. If you’ve kept up with any of the React discussions over time, you might be thinking, “Jim, Facebook is OK with calling dispatch directly on an XHR response, rather than use another ActionCreator”. Absolutely — and that makes perfect sense when your implementation gives your util modules (like remote data APIs) a handle to the dispatcher. With lux, we opted for the gateway to the dispatcher to be via message contract, and removed the need for the dispatcher to be a dependency of any module.

So if every input is an action, this means we might have actions in our system that none of our stores care about. Other actions might be of interest to both a store and our remote data API. The value of how this complements and forces you into the pit of unidirectional data flow success can be illustrated in this image:

17
Unidirectional data flow in lux.js. (View large version18)

In the above scenario, a user clicked a button on the page that resulted in a server request. When the server responds, the response is published as a new action. While we know that the two actions are related, modeling things this way reinforces the avoidance of cascading updates, and it means your app’s behavior will be capable of handling data being pushed to it, not just pulled through HTTP requests.

What if we wanted to update the UI to reflect that data is loading? It’s as easy as having the appropriate store handle the same action:

19
Unidirectional data flow in lux.js: Update the UI. (View large version20)

Another benefit of treating every input as an action: it makes it easy to see what behaviors are possible in your app. For example, here’s the output of calling lux.utils.printActions():

Unidirectional data flow in lux.js21
Unidirectional data flow in lux.js: Output of calling lux.utils.printActions(). (View large version22)

Lux also provides a utility method to view what stores would participate in handling an action, and in what order: lux.utils.printStoreDepTree(actionName):

Unidirectional data flow in lux.js23
Unidirectional data flow in lux.js: lux.utils.printStoreDepTree(actionName). (View large version24)

Lux + Ajax Examples

We’ve resisted any temptation to be too prescriptive when it comes to how you should interact with remote endpoints in lux. The main guideline we follow is to wrap your remote access in a developer-friendly API in the client (rather than scatter Ajax requests throughout the codebase!), and make that API wrapper an ActionListener and ActionCreator. For example, let’s look at a couple of conceptual approaches you can take:

Plain Ajax

The example below only shows the relevant portions of each piece. Our component publishes an action message for the cartCheckout action, and our WebApi wrapper listens for it. Notice that our response handler for the Ajax call actually publishes a new action message:

// in a CartContainer.jsx module
var CartContainer = React.createClass({
  // other methods, properties, etc.

  onCheckoutClicked: function() {
    var products = this.state.products;
    if (!products.length) {
      return;
    }
    this.cartCheckout(products);
  }
});

// In a WebApi.js module
var webApi = lux.actionCreatorListener({
  handlers: {
    cartCheckout: function(products) {
      $.ajax({
        url: "cart/checkout",
        method: "POST",
        data: products
      }).then(
        function(data) {
          this.publishAction("successCheckout", data);
        }.bind(this),
        cartErrorHandler
      );
    }
  }
});
How We Use halon

One of the many things we’ve grown to love about hypermedia resources is the built-in discoverability. Instead of having to hard-code specific links (as in the example above), halon allows us to follow links returned with resources, so the only URL we have to know is where we go to get the OPTIONS. In this approach, our WebApi module initializes halon (which results in an OPTIONS request to the server), and the resulting instance will contain the top-level resources we can act on, with their “actions” exposed as methods. In this case we have a cart resource that exposes a checkout action:

// in a CartContainer.jsx module
var CartContainer = React.createClass({
  // other methods, properties, etc.

  onCheckoutClicked: function() {
    var products = this.state.products;
    if (!products.length) {
      return;
    }
    this.cartCheckout(products);
  }
});

// In a WebApi.js module
var hal = halon( {
  root: "https://some-server.com/api",
  adapter: halon.jQueryAdapter( $ ),
  version: 1
} );
var webApi = lux.actionCreatorListener({
  handlers: {
    cartCheckout: function(products) {
      hal.cart.checkout(products)
        .then(
          function(data) {
            this.publishAction("successCheckout", data);
          }.bind(this),
          cartErrorHandler
        );
    }
  }
});

Stores And Synchronicity

Actions, Stores And Remote Data I/O

I believe a classic pitfall to those rolling their own Flux implementations is putting remote data I/O in stores. In the first version of lux, I not only fell into this pit, I pulled out a golden shovel and dug even deeper. Our stores had the ability to make HTTP calls — and as a result, the need for action dispatch cycles to be asynchronous was unavoidable. This introduced a ripple of bad side effects:

  • Retrieving data from a store was an asynchronous operation, so it wasn’t possible to synchronously use a store’s state in a controller ciew’s getInitialState method.
  • We found that requiring asynchronous reads of store state discouraged the use of read-only helper methods on stores.
  • Putting I/O in stores led to actions being initiated by stores (e.g. on XHR responses or WebSocket events). This quickly undermined the gains from unidirectional data flow. Flux stores publishing their own actions could lead to cascading updates — the very thing we wanted to avoid!

I think the temptation to fall into this pit has to do with the trend of client-side frameworks to date. Client-side models are often treated as write-through caches for server-side data. Complex server/client synchronization tools have sprung up, effectively encouraging a sort of two-way binding across the server/client divide. Yoda said it best: you must unlearn what you have learned.

About the time I realized I’d be better off making lux stores synchronous, I read Reto Schläpfer’s post “Async requests with React.js and Flux, revisited25”. He had experienced the same pain, and the same realization. Making lux stores synchronous, from the moment the dispatcher begins handling an action to the moment stores emit change events, made our app more deterministic and enabled our controller views to synchronously read store state as they initialized. We finally felt like we’d found the droids we were looking for.

Let’s take a look at one of the lux stores in the flux-comparison example:

var CartStore = new lux.Store( {
  namespace: "cart",

  state: { products: { } },

  handlers: {
    addToCart: {
      waitFor: [ 'products' ],
      handler: function( product ) {
        var newState = this.getState();
        newState.products[ product.id ] = (
          newState.products[ product.id ] ||
          assign( products.getProduct( product.id ), { quantity: 0 } )
        );
        newState.products[ product.id ].quantity += 1;
        this.setState( newState );
      }
    },
    cartCheckout: function() {
      this.replaceState( { products: {} } );
    },
    successCheckout: function( products ) {
      // this can be used to redirect to success page, etc.
      console.log( 'YOU BOUGHT:' );
      if ( typeof console.table === "function" ) {
        console.table( products );
      } else {
        console.log( JSON.stringify( products, null, 2 ) );
      }
    }
  },

  getProduct: function( id ) {
    return this.getState().products[ id ];
  },

  getAddedProducts: function() {
    var state = this.getState();
    return Object.keys( state.products ).map( function( id ) {
      return state.products[ id ];
    } );
  },

  getTotal: function() {
    var total = 0;
    var products = this.getState().products;
    for (var id in products) {
      var product = products[ id ];
      total += product.price * product.quantity;
    }
    return total.toFixed( 2 );
  }
} );

A lux store contains (at least) a handlers property and a namespace. The names of the keys on the handlers property match the action type that they handle. In keeping with Flux principles, it’s possible for lux stores to wait on other stores before executing their handler. The stores you need to wait on can be specified on a per-action basis. The addToCart handler above is a good example. In the waitFor array, you specify the namespaces of any other store you need to wait on — this handler waits on the “products” store. The dispatcher determines the order in which stores need to execute their handlers at runtime, so there’s no need to worry about managing the order yourself in your store logic. (Note that if you don’t need to wait on any other stores, the handler value can be just the handler function itself rather than the object literal representation on addToCart above.)

You can also set initial state on the store, as we’re doing above, and provide top-level methods that are used for reading data (the lux store prototype provides the getState() method). Since store handlers execute synchronously, you can safely read a store’s state from any component’s getInitialState method, and you can be assured that no other action will interrupt or mutate store state while another action is being handled.

lux stores also provide setState and replaceState methods, but if you attempt to invoke them directly, an exception will be thrown. Those methods can only be invoked during a dispatch cycle; we put this rather heavy-handed opinion in place to reinforce the guideline that only stores mutate their own state, and that’s done in a handler.

Plays Well With Others

Another key lesson for our team: it needs to be simple for lux and non-React/non-lux (external) instances to play well together. To that end, lux provides mixins that can be used by external instances.

Store Mixin

The store mixin enables you to listen for store change events. For example, this snippet shows an instance that’s wired to listen to our ProductStore and CartStore:

var storeLogger = lux.mixin({
  stores: {
    listenTo: [ "products", "cart" ],
    onChange: function() {
      console.log( "STORE LOGGER: Received state change event" );
    },
  }
}, lux.mixin.store);

ActionCreator Mixin

The actionCreator mixin gives the instance a publishAction( actionName, arg1, arg2…) method. This method handles packaging the metadata about the action into a message payload and then publishes it (if you’ve created a custom ActionCreator that does more than just publish the action message, it will invoke that behavior):

// calling lux.actionCreator is a convenience wrapper around
// lux.mixin( target, lux.mixin.actionCreator );
var creator = lux.actionCreator( {
  doAThing: function() {
    this.publishAction( "doJazzHands", "hey, I can lux, too!", true, "story" );
  }
} );

ActionListener Mixin

The actionListener mixin wires the instance into postal, so that it listens for any lux action messages. When a message arrives, it checks the handlers property for a matching handler and invokes it:

var listener = lux.actionListener({
  handlers: {
    doJazzHands: function(msg, someBool, lastArg) {
      console.log(msg, someBool, lastArg); // -> hey, I can lux, too! true story
    }
  }
});

Why Not Both?

It’s not uncommon — especially if remote data API wrappers are involved — to need both actionCreator and actionListener mixins. lux provides a convenience method for this, unsurprisingly named actionCreatorListener. In the flux-comparison example, the wrapper around the mock remote data API uses this:

// WebAPIUtils.js
var shop = require( '../../../common/api/shop' );
var lux = require( 'lux.js' );

module.exports = lux.actionCreatorListener( {
  handlers: {
    cartCheckout: function( products ) {
      shop.buyProducts( products, function() {
        this.publishAction( "successCheckout", products );
      }.bind( this ) );
    },
    getAllProducts: function() {
      shop.getProducts( function( products ) {
        this.publishAction( "receiveProducts", products );
      }.bind( this ) );
    },
  }
} );

The above module listens for the cartCheckout and getAllProducts actions. As it handles them, it uses the publishAction method (simulating how a server response would initiate a new Action).

So far, the mixins have covered every need we’ve had to make non-lux/non-React instances play well with lux. If those weren’t enough, though, the underlying message contracts for actions and store update notifications are very simple, and could serve as an alternative. In fact, we plan to use those in some future Chrome dev tools extensions for lux.

Wrapping Up

As I’ve looked through other Flux implementations, I’ve been encouraged to see that these principles are frequently present in them as well. The number of options available can feel overwhelming, but overall I find it an encouraging development. Solid and successful patterns like Flux will, by their very nature, encourage multiple implementations. If our experience is any indication, keeping these principles in mind can help guide you as you select, or write, the Flux implementation you need.

(rb, ml, og)

Footnotes

  1. 1 http://facebook.github.io/react/
  2. 2 http://facebook.github.io/react/blog/2014/05/06/flux.html
  3. 3 http://facebook.github.io/react/
  4. 4 http://facebook.github.io/react/docs/jsx-in-depth.html
  5. 5 http://facebook.github.io/react/docs/getting-started.html
  6. 6 https://facebook.github.io/flux/
  7. 7 https://github.com/LeanKit-Labs/lux.js
  8. 8 http://facebook.github.io/flux/docs/overview.html#content
  9. 9 https://github.com/LeanKit-Labs/lux.js
  10. 10 https://github.com/voronianski/flux-comparison
  11. 11 https://github.com/postaljs/postal.js
  12. 12 https://github.com/LeanKit-Labs/halon
  13. 13 https://tools.ietf.org/html/draft-kelly-json-hal-06
  14. 14 http://timelessrepo.com/haters-gonna-hateoas
  15. 15 http://martinfowler.com/articles/richardsonMaturityModel.html
  16. 16 http://phlyrestfully.readthedocs.org/en/latest/halprimer.html
  17. 17 http://www.smashingmagazine.com/wp-content/uploads/2015/05/01-luxdataflow1-opt.png
  18. 18 http://www.smashingmagazine.com/wp-content/uploads/2015/05/01-luxdataflow1-opt.png
  19. 19 http://www.smashingmagazine.com/wp-content/uploads/2015/05/02-luxdataflow2-opt.png
  20. 20 http://www.smashingmagazine.com/wp-content/uploads/2015/05/02-luxdataflow2-opt.png
  21. 21 http://www.smashingmagazine.com/wp-content/uploads/2015/05/03-luxPrintActions-opt.png
  22. 22 http://www.smashingmagazine.com/wp-content/uploads/2015/05/03-luxPrintActions-opt.png
  23. 23 http://www.smashingmagazine.com/wp-content/uploads/2015/05/04-luxPrintStoreDepTree-opt.png
  24. 24 http://www.smashingmagazine.com/wp-content/uploads/2015/05/04-luxPrintStoreDepTree-opt.png
  25. 25 http://www.code-experience.com/async-requests-with-react-js-and-flux-revisited/

The post Qualities Of Good Flux Implementations appeared first on Smashing Magazine.

Categories: Others Tags:

GraphicStock Offers Affordable Stock Photography and Design Elements

June 22nd, 2015 No comments

As creative professionals, we always need proper stock material. Time does not allow to shoot all necessary photos ourselves, nor does it allow to create all required design elements from scratch. If you do you will run into problems sooner or later as either your projects take too long to come to an end or your clients don’t want to pay all that extra money anymore. Especially not for something they “can get on the Internet for free”. That’s why being on the lookout for good stock material is a survival strategy you shouldn’t miss. Today we will introduce you to GraphicStock, one of these all-in-one sites with an uncomplicated flat fee… GraphicStock: Unlimited Access at a Flat Fee GraphicStock is an affordable, subscription-based stock media site that gives you unlimited access to premium stock footage. That’s a very short yet fitting description of what GraphicStock actually is. The most obvious unique selling proposition is the uncomplicated flat rate it offers. Other than other image providers GraphicStock has just one price to be remembered. The flat fee is 49 USD per month, and that’s it – download galore. There are no further limitations, such as x files in y days […]

Categories: Others Tags:

Jotform Rescues Your Web Forms and Grows Further

June 19th, 2015 No comments

It comes without further explanation that we here at Noupe are big fans of JotForm. If you are one of our hundreds of thousands of frequent readers, you were unable to get around the praises we shared. The year 2015 is another good year in the history of the service as they continue to innovate. Furthermore, Adobe has added its part to the continuous growth of my favorite forms platform… Rescue Your Web Forms as Adobe Forms Central Closes It is up until next Monday, the 22nd of June, that you can still use Adobe’s FormCentral service to create forms and collect data. Starting following Tuesday, you will no longer be able to create new forms or collect new data but you will still be able to download existing data from existing forms. Then, on July 28th all your forms and form data will go down the drain. It’s high time for action. Should you not know what FormsCentral is or better was chances are you need not do anything 😉 For those of you who are still curious, Adobe FormsCentral was, simply speaking, an online collector backend for PDF forms. Users would create fillable forms as PDFs and then […]

Categories: Others Tags:

A Detailed Guide To WordPress Custom Page Templates

June 19th, 2015 No comments
The WordPress template hierarchy.

I like to think of WordPress as the gateway drug of web development. Many people who get started using the platform are initially merely looking for a comfortable (and free) way to create a simple website. Some Googling and consultation of the WordPress Codex1 later, it’s done and that should be it. Kind of like “I’m just going to try it once.”

However, a good chunk of users don’t stop there. Instead, they get hooked. Come up with more ideas. Experiment. Try out new plugins. Discover Firebug2. Boom. Soon there is no turning back. Does that sound like your story? As a WordPress user it is only natural to want more and more control over your website. To crave custom design, custom functionality, custom everything.

Luckily, WordPress is built for exactly that. Its flexible structure and compartmentalized architecture allows anyone to change practically anything on their site.

Among the most important tools in the quest for complete website control are page templates. They allow users to dramatically alter their website’s design and functionality. Want a customized header for your front page? Done. An additional sidebar only for your blog page? No problem. A unique 404 error page? Be. My. Guest.

If you want to know how WordPress page templates can help you achieve that, read on. But first, a little background information.

Template Files In WordPress

What are we talking about when we speak of templates in the context of WordPress? The short version is that templates are files which tell WordPress how to display different types of content.

The slightly longer version: every time someone sends a request to view part of your website, the WordPress platform will figure out what content they want to see and how that specific part of your website should be rendered.

For the latter, WordPress will attempt to use the most appropriate template file found within your theme. Which one is decided on the basis of a set order, the WordPress template hierarchy3. You can see what this looks like in the screenshot below or in this interactive version4.

5
The WordPress template hierarchy. (Image credit: WordPress Codex6)(View large version7)

The template hierarchy is a list of template files WordPress is familiar with that are ranked to determine which file takes precedence over another.

You can think of it as a decision tree. When WordPress tries to decide how to display a given page, it works its way down the template hierarchy until it finds the first template file that fits the requested page. For example, if somebody attempted to access the address http://yoursite.com/category/news, WordPress would look for the correct template file in this order:

  1. category-{slug}.php: in this case category-news.php
  2. category-{id}.php>: if the category ID were 5, WordPress would try to find a file named category-5.php
  3. category.php
  4. archive.php
  5. index.php

At the bottom of the hierarchy is index.php. It will be used to display any content which does not have a more specific template file attached to its name. If a template file ranks higher in the hierarchy, WordPress will automatically use that file in order to display the content in question.

Page Templates And Their Use

For pages, the standard template is usually the aptly named page.php. Unless there is a more specific template file available (such as archive.php for an archive page), WordPress will use page.php to render the content of all pages on your website.

However, in many cases it might be necessary to change the design, look, feel or functionality of individual parts of your website. This is where page templates come into play. Customized page templates allow you to individualize any part of your WordPress site without affecting the rest of it.

You might have already seen this at work. For example, many WordPress themes today come with an option to change your page to full width, add a second sidebar or switch the sidebar’s location. If that is the case for yours, it was probably done through template files. There are several ways to accomplish this and we’ll go over them later.

First, however, a word of caution: since working with templates involves editing and changing files in your active theme, it’s always a good idea to go with a child theme when making these kinds of customizations. That way you don’t run the danger of having your changes overwritten when your parent theme gets updated.

How To Customize Any Page In WordPress

There are three basic ways to use custom page templates in WordPress: adding conditional statements to an existing template; creating specific page templates which rank higher in the hierarchy; and directly assigning templates to specific pages. We will take a look at each of these in turn.

Using Conditional Tags In Default Templates

An easy way to make page-specific changes is to add WordPress’s many conditional tags8 to a template already in use. As the name suggests, these tags are used to create functions which are only executed if a certain condition is met. In the context of page templates, this would be something along the line of “Only perform action X on page Y.”

Typically, you would add conditional tags to your theme’s page.php file (unless, of course, you want to customize a different part of your website). They enable you to make changes limited to the homepage, front page, blog page or any other page of your site.

Here are some frequently used conditional tags:

  1. is_page(): to target a specific page. Can be used with the page’s ID, title, or URL/name.
  2. is_home(): applies to the home page.
  3. is_front_page(): targets the front page of your site as set under Settings ? Reading
  4. is _category(): condition for a category page. Can use ID, title or URL/name like is_page() tag.
  5. is_single(): for single posts or attachments
  6. is_archive(): conditions for archive pages
  7. is_404(): applies only to 404 error pages

For example, when added to your page.php in place of the standard get_header(); tag, the following code will load a custom header file named header-shop.php when displaying the page http://yoursite.com/products.

if ( is_page('products') ) {
  get_header( 'shop' );
} else {
  get_header();
}

A good use case for this would be if you have a shop on your site and you need to display a different header image or customized menu on the shop page. You could then add these customization in header-shop.php and it would show up in the appropriate place.

However, conditional tags are not limited to one page. You can make several statements in a row like so:

if ( is_page('products') ) {
  get_header( 'shop' );
} elseif ( is_page( 42 ) ) {
  get_header( 'about' );
} else {
  get_header();
}

In this second example, two conditions will change the behavior of different pages on your site. Besides loading the aforementioned shop-specific header file, it would now also load a header-about.php on a page with the ID of 42. For all other pages the standard header file applies.

To learn more about the use of conditional tags, the following resources are highly recommended:

Creating Page-Specific Files In The WordPress Hierarchy

Conditional tags are a great way to introduce smaller changes to your page templates. Of course, you can also create larger customizations by using many conditional statements one after the other. I find this a very cumbersome solution, however, and would opt for designated template files instead.

One way to do this is to exploit the WordPress template hierarchy. As we have seen, the hierarchy will traverse a list of possible template files and choose the first one it can find that fits. For pages, the hierarchy looks like this:

  • Custom page template
  • page-{slug}.php
  • page-{id}.php
  • page.php
  • index.php

In first place are custom page templates which have been directly assigned to a particular page. If one of those exists, WordPress will use it no matter which other template files are present. We will talk more about custom page templates in a bit.

After that, WordPress will look for a page template that includes the slug of the page in question. For example, if you include a file named page-about.php in your theme files, WordPress will use this file to display your ‘About’ page or whichever page can be found under http://www.yoursite.com/about.

Alternatively, you can achieve the same by targeting your page’s ID. So if that same page has an ID of 5, WordPress will use the template file page-5.php before page.php if it exists; that is, only if there isn’t a higher-ranking page template available.

(BTW, you can find out the ID for every page by hovering over its title under ‘All Pages’ in your WordPress back-end. The ID will show up in the link displayed by your browser.)

Assigning Custom Page Templates

Besides providing templates in a form that WordPress will use automatically, it is also possible to manually assign custom templates to specific pages. As you can see from the template hierarchy, these will trump any other template file present in the theme folder.

Just like creating page-specific templates for the WordPress hierarchy, this requires you to provide a template file and then link it to whichever page you want to use it for. The latter can be done in two different ways you might already be familiar with. Just in case you aren’t, here is how to do it.

1. Assigning Custom Page Templates From The WordPress Editor

In the WordPress editor, you find an option field called ‘Page Attributes’ with a drop-down menu under ‘Template’.

11
Page Attributes in the WordPress editor. (View large version12)

Clicking on it will give you a list of available page templates on your WordPress website. Choose the one you desire, save or update your page and you are done.

Available templates under Page Attributes.13
Available templates under Page Attributes. (View large version14)
2. Setting A Custom Template Via Quick Edit

The same can also be achieved without entering the WordPress editor. Go to ‘All Pages’ and hover over any item in the list there. A menu will become visible that includes the ‘Quick Edit’ item.

Click on it to edit the page settings directly from the list. You will see the same drop-down menu for choosing a different page template. Pick one, update the page and you are done.

Not so hard after all, is it? But what if you don’t have a custom page template yet? How do you create it so that your website looks exactly the way you want it? Don’t worry, that’s what the next part is all about.

A Step-By-Step Guide To Creating Custom Page Templates

Putting together customized template files for your pages is not that hard but here are a few details you have to pay attention to. Therefore, let’s go over the process bit-by-bit.

1. Find The Default Template

A good way is to start by copying the template which is currently used by the page you want to modify. It’s easier to modify existing code than to write an entire page from scratch. In most cases this will be the page.php file.

(If you don’t know how to find out which template file is being used on the page you want to edit, the plugin What The File15 will prove useful.)

I will be using the Twenty Twelve theme for demonstration. Here is what its standard page template looks like:

<?php
/**
 * The template for displaying all pages
 *
 * This is the template that displays all pages by default.
 * Please note that this is the WordPress construct of pages
 * and that other 'pages' on your WordPress site will use a
 * different template.
 *
 * @package WordPress
 * @subpackage Twenty_Twelve
 * @since Twenty Twelve 1.0
 */
get_header(); ?>

  <div id="primary" class="site-content">
    <div id="content" role="main">

      <?php while ( have_posts() ) : the_post(); ?>
        <?php get_template_part( 'content', 'page' ); ?>
        <?php comments_template( '', true ); ?>
      <?php endwhile; // end of the loop. ?>

    </div><!-- #content -->
  </div><!-- #primary -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

As you can see, nothing too fancy here: the usual calls for the header and footer, and the loop in the middle. The page in question looks like this:

The default page template in the Twenty Twelve theme.16
The default page template in the Twenty Twelve theme. (View large version17)

2. Copy And Rename The Template File

After identifying the default template file, it’s time to make a copy. We will use the duplicated file in order to make the desired changes to our page. For that we will also have to rename it. Can’t have two files of the same name, that’s just confusing for everyone.

You are free to give the file any name you like as long as it doesn’t start with any of the reserved theme filenames18. So don’t be naming it page-something.php or anything else that would make WordPress think it is a dedicated template file.

It makes sense to use a name which easily identifies what this template file is used for, such as my-custom-template.php. In my case I will go with custom-full-width.php.

3. Customize The Template File Header

Next we have to tell WordPress that this new file is a custom page template. For that, we will have to adjust the file header in the following way:

<?php
/*
 * Template Name: Custom Full Width
 * Description: Page template without sidebar
 */

// Additional code goes here...

The name under ‘Template Name’ is what will be displayed under ‘Page Attributes’ in the WordPress editor. Make sure to adjust it to your template name.

4. Customize The Code

Now it’s time to get to the meat and potatoes of the page template: the code. In my example, I merely want to remove the sidebar from my demo page.

This is relatively easy, as all I have to do is remove from my page template since that’s what is calling the sidebar. As a consequence, my custom template ends up looking like this:

<?php
/*
 * Template Name: Custom Full Width
 * Description: Page template without sidebar
 */

get_header(); ?>

<div id="primary" class="site-content">
  <div id="content" role="main">

    <?php while ( have_posts() ) : the_post(); ?>
      <?php get_template_part( 'content', 'page' ); ?>
      <?php comments_template( '', true ); ?>
    <?php endwhile; // end of the loop. ?>

  </div><!-- #content -->
</div><!-- #primary -->

<?php get_footer(); ?>

5. Upload The Page Template

After saving my customized file, it is now time to upload it to my website. Custom page templates can be saved in several places to be recognized by WordPress:

  • Your active (child) theme’s folder
  • The folder of your main parent theme
  • A subfolder within either of these

I personally like to create a folder named page_templates in my child theme and place any customized templates in there. I find this easiest to retain an overview over my files and customizations.

6. Activate The Template

As a last step, you need to activate the page template. As mentioned earlier, this is done under Page Attributes ? Templates in the WordPress editor. Save, view the page and voilà! Here is my customized page without a sidebar:

Customized page template without the sidebar.19
Customized page template without the sidebar. (View large version20)

Not so hard, is it? Don’t worry, you will quickly get the hang of it. To give you a better impression of what to use these page templates for, I will demonstrate additional use cases (including the code) for the remainder of the article.

Five Different Ways To Use Page Templates

As already mentioned, page templates can be employed for many different purposes. You can customize pretty much anything on any page with their help. Only your imagination (and coding abilities) stand in your way.

1. Full-Width Page Template

The first case we will look at is an advanced version of the demo template we created above. Up there, we already removed the sidebar by deleting from the code. However, as you have seen from the screenshot this does not actually result in a full-width layout since the content section stays on the left.

To address this, we need to deal with the CSS, in particular this part:

.site-content {
  float: left;
  width: 65.1042%;
}

The width attribute limits the element which holds our content to 65.1042% of the available space. We want to increase this.

If we just change it to 100%, however, this will affect all other pages on our site, which is far from what we want. Therefore, the first order here is to change the primary div‘s class in our custom template to something else, like class="site-content-fullwidth". The result:

<?php
/*
 * Template Name: Custom Full Width
 * Description: Page template without sidebar
 */

get_header(); ?>

<div id="primary" class="site-content-fullwidth">
  <div id="content" role="main">

    <?php while ( have_posts() ) : the_post(); ?>
      <?php get_template_part( 'content', 'page' ); ?>
      <?php comments_template( '', true ); ?>
    <?php endwhile; // end of the loop. ?>

  </div><!-- #content -->
</div><!-- #primary -->

<?php get_footer(); ?>

Now we can adjust the CSS for our new custom class:

.site-content-fullwidth {
  float: left;
  width: 100%;
}

As a result, the content now stretches all the way across the screen.

The custom page template at full width.21
The custom page template at full width. (View large version22)

2. Dynamic 404 Error Page With Widget Areas

The 404 error page is where every person lands who tries to access a page on your website that doesn’t exist, be it through a typo, a faulty link or because the page’s permalink has changed.

Despite the fact that getting a 404 is disliked by everyone on the Internet, if you are running a website the 404 error page is of no little importance. Its content can be the decisive factor on whether someone immediately abandons your site or sticks around and checks out your other content.

Coding a customized error page from scratch is cumbersome, especially if you are not confident in your abilities. A better way is to build widget areas into your template so you can flexibly change what is displayed there by drag and drop.

For this we will grab and edit the 404.php file that ships with Twenty Twelve (template hierarchy, remember?). However, before we change anything on there, we will first create a new widget by inserting the following code into our functions.php file:

register_sidebar( array(
  'name' => '404 Page',
  'id' => '404',
  'description'  => __( 'Content for your 404 error page goes here.' ),
  'before_widget' => '<div id="error-box">',
  'after_widget' => '</div>',
  'before_title' => '<h3 class="widget-title">',
  'after_title' => '</h3>'
) );

This should display the newly created widget in your WordPress back-end. To make sure that it actually pops up on the site, you need to add the following line of code to your 404 page in the appropriate place:

<?php dynamic_sidebar( '404' ); ?>

In my case, I want to replace the search form () inside the template with my new widget, making for the following code:

<?php
/**
 * The template for displaying 404 pages (Not Found)
 *
 * @package WordPress
 * @subpackage Twenty_Twelve
 * @since Twenty Twelve 1.0
 */

get_header(); ?>

<div id="primary" class="site-content">
  <div id="content" role="main">

    <article id="post-0" class="post error404 no-results not-found">
      <header class="entry-header">
        <h1 class="entry-title"><?php _e( 'This is somewhat embarrassing, isn&amp;rsquo;t it?', 'twentytwelve' ); ?></h1>
      </header>

      <div class="entry-content">
        <?php dynamic_sidebar( '404' ); ?>
      </div><!-- .entry-content -->
    </article><!-- #post-0 -->

  </div><!-- #content -->
</div><!-- #primary -->

<?php get_footer(); ?>

After uploading the template to my site, it’s time to populate my new widget area:

404 page template widget.23
404 page template widget. (View large version24)

If I now take a look at the 404 error page, my newly created widgets show up there:

Customized 404 page.25
Customized 404 page. (View large version26)

3. Page Template For Displaying Custom Post Types

Custom post types are a great way to introduce content that has its own set of data points, design and other customizations. A favorite use case for these post types are review items such as books and movies. In our case we want to build a page template that shows portfolio items.

We first need to create our custom post type (CPT). This can be done manually or via plugin. One plugin option I can wholeheartedly recommend is Types27. It lets you easily create custom post types and custom fields.

Install and activate Types, add a custom post, make sure its slug is ‘portfolio’, customize any fields you need (such as adding a featured image), adjust any other options, and save.

Now, that we have our portfolio post type, we want it to show up on our site. The first thing we’ll do is create the page in question. Be aware that if you chose ‘portfolio’ as the slug of your CPT, the page can not have the same slug. I went with my clients-portfolio and also added some example text.

Portfolio page without a custom page template.28
Portfolio page without a custom page template. (View large version29)

After adding a few items in the ‘portfolio’ post type section, we want them to show up on our page right underneath the page content.

To achieve this we will again use a derivative of the page.php file. Copy it, call it portfolio-template.php and change the header to this:

<?php
/*
 * Template Name: Portfolio Template
 * Description: Page template to display portfolio custom post types 
 * underneath the page content
 */
 

However, in this case we will have to make a few changes to the original template. When you take a look at the code of page.php, you will see that it calls another template file in the middle, named content-page.php (where it says ). In that file we find the following code:

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
  <header class="entry-header">
    <?php if ( ! is_page_template( 'page-templates/front-page.php' ) ) : ?>
    <?php the_post_thumbnail(); ?>
    <?php endif; ?>
    <h1 class="entry-title"><?php the_title(); ?></h1>
  </header>

  <div class="entry-content">
    <?php the_content(); ?>
    <?php wp_link_pages( array( 'before' => '<div class="page-links">' . __( 'Pages:', 'twentytwelve' ), 'after' => '</div>' ) ); ?>
  </div><!-- .entry-content -->
  <footer class="entry-meta">
    <?php edit_post_link( __( 'Edit', 'twentytwelve' ), '<span class="edit-link">', '</span>' ); ?>
  </footer><!-- .entry-meta -->
</article><!-- #post -->

As you can see, it is here that the page title and content are called. Since we definitely want those on our portfolio site, we will need to copy the necessary parts of this template to our page.php file. The result looks like this:

get_header(); ?>

<div id="primary" class="site-content">
  <div id="content" role="main">

    <?php while ( have_posts() ) : the_post(); ?>
      <header class="entry-header">
        <?php the_post_thumbnail(); ?>
        <h1 class="entry-title"><?php the_title(); ?></h1>
      </header>

      <div class="entry-content">
        <?php the_content(); ?>
      </div><!-- .entry-content -->
      
      <?php comments_template( '', true ); ?>
    <?php endwhile; // end of the loop. ?>

  </div><!-- #content -->
</div><!-- #primary -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

To get the portfolio items onto our page, we will add the following code right beneath the the_content() call.

<?php
  $args = array(
    'post_type' => 'portfolio', // enter custom post type
    'orderby' => 'date',
    'order' => 'DESC',
  );
   
  $loop = new WP_Query( $args );
  if( $loop->have_posts() ):
  while( $loop->have_posts() ): $loop->the_post(); global $post;
    echo '<div class="portfolio">';
    echo '<h3>' . get_the_title() . '</h3>';
    echo '<div class="portfolio-image">'. get_the_post_thumbnail( $id ).'</div>';
    echo '<div class="portfolio-work">'. get_the_content().'</div>';
    echo '</div>';
  endwhile;
  endif;
?>

This will make the CPT show up on the page:

The custom portfolio template.30
The custom portfolio template. (View large version31)

I’m sure we all agree that it looks less than stellar, so some styling is in order.

/* Portfolio posts */

.portfolio {
  -webkit-box-shadow: 0px 2px 2px 0px rgba(50, 50, 50, 0.75);
  -moz-box-shadow:    0px 2px 2px 0px rgba(50, 50, 50, 0.75);
  box-shadow:         0px 2px 2px 0px rgba(50, 50, 50, 0.75);
  margin: 0 0 20px;
  padding: 30px;
}
.portfolio-image {
  display: block;
  float: left;
  margin: 0 10px 0 0;
  max-width: 20%;
}
.portfolio-image img {
  border-radius: 0;
}
.portfolio-work {
  display: inline-block;
  max-width: 80%;
}
.portfolio h3{
  border-bottom: 1px solid #999;
  font-size: 1.57143rem;
  font-weight: normal;
  margin: 0 0 15px;
  padding-bottom: 15px;
}

Much better, don’t you think?

The custom portfolio template with styling.32
The custom portfolio template with styling. (View large version33)

And here is the entire code for the portfolio page template:

<?php
/*
 * Template Name: Portfolio Template
 * Description: Page template to display portfolio custom post types 
 * underneath the page content
 */

get_header(); ?>

<div id="primary" class="site-content">
  <div id="content" role="main">

    <?php while ( have_posts() ) : the_post(); ?>
        
      <header class="entry-header">
        <?php the_post_thumbnail(); ?>
        <h1 class="entry-title"><?php the_title(); ?></h1>
      </header>

      <div class="entry-content">
        <?php the_content(); ?>
        <?php
          $args = array(
            'post_type' => 'portfolio', // enter custom post type
            'orderby' => 'date',
            'order' => 'DESC',
          );
              
          $loop = new WP_Query( $args );
          if( $loop->have_posts() ):
          while( $loop->have_posts() ): $loop->the_post(); global $post;
            echo '<div class="portfolio">';
            echo '<h3>' . get_the_title() . '</h3>';
            echo '<div class="portfolio-image">'. get_the_post_thumbnail( $id ).'</div>';
            echo '<div class="portfolio-work">'. get_the_content().'</div>';
            echo '</div>';
          endwhile;
          endif;
        ?>
      </div><!-- #entry-content -->
      <?php comments_template( '', true ); ?>               
    <?php endwhile; // end of the loop. ?>                
  </div><!-- #content -->
</div><!-- #primary -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

4. Contributor Page With Avatar images

Next up in our page template use cases is a contributor page. We want to set up a list of authors on our website, including their images and the number of posts they have published under their name. The end result will look like this:

The completed custom contributors page.34
The completed custom contributors page. (View large version35)

We will again start out with our hybrid file from before and add the code for the contributor list to it. But what if you don’t know how to create such a thing? No worries, you can get by with intelligent stealing.

You see, the Twenty Fourteen default theme comes with a contributor page by default. You can find its template in the page-templates folder with the name contributors.php.

When looking into the file, however, you will only find the following call in there: twentyfourteen_list_authors();. Luckily, as an avid WordPress user you now conclude that this probably refers to a function in Twenty Fourteen’s function.php file and you would be right.

From what we find in there, the part that interests us is this:

<?php
// Output the authors list.
$contributor_ids = get_users( array(
  'fields'  => 'ID',
  'orderby' => 'post_count',
  'order'   => 'DESC',
  'who'     => 'authors',
));

foreach ( $contributor_ids as $contributor_id ) :
$post_count = count_user_posts( $contributor_id );
  // Move on if user has not published a post (yet).
  if ( ! $post_count ) {
    continue;
  }
?>

<div class="contributor">
  <div class="contributor-info">
    <div class="contributor-avatar"><?php echo get_avatar( $contributor_id, 132 ); ?></div>
    <div class="contributor-summary">
      <h2 class="contributor-name"><?php echo get_the_author_meta( 'display_name', $contributor_id ); ?></h2>
      <p class="contributor-bio">
        <?php echo get_the_author_meta( 'description', $contributor_id ); ?>
      </p>
      <a class="button contributor-posts-link" href="<?php echo esc_url( get_author_posts_url( $contributor_id ) ); ?>">
        <?php printf( _n( '%d Article', '%d Articles', $post_count, 'twentyfourteen' ), $post_count ); ?>
      </a>
    </div><!-- .contributor-summary -->
  </div><!-- .contributor-info -->
</div><!-- .contributor -->

<?php
endforeach;
?>

We will again add it below the call for the_content() with the following result:

The unstyled custom contributors page.36
The unstyled custom contributors page. (View large version37)

Now for a little bit of styling:

/* Contributor page */

.contributor {
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing:      border-box;
  display: inline-block;
  padding: 48px 10px;
}
.contributor p {
  margin-bottom: 1rem;
}
.contributor-info {
  margin: 0 auto 0 168px;
}
.contributor-avatar {
  border: 1px solid rgba(0, 0, 0, 0.1);
  float: left;
  line-height: 0;
  margin: 0 30px 0 -168px;
  padding: 2px;
}
.contributor-avatar img{
  border-radius: 0;
}
.contributor-summary {
  float: left;
}
.contributor-name{
  font-weight: normal;
  margin: 0 !important;
}
.contributor-posts-link {
  background-color: #24890d;
  border: 0 none;
  border-radius: 0;
  color: #fff;
  display: inline-block;
  font-size: 12px;
  font-weight: 700;
  line-height: normal;
  padding: 10px 30px 11px;
  text-transform: uppercase;
  vertical-align: bottom;
}
.contributor-posts-link:hover {
  color: #000;
  text-decoration: none;
}

And that should be it. Thanks Twenty Fourteen!

5. Customized Archive Page

Twenty Twelve comes with its own template for archive pages. It will jump into action, for example, when you attempt to view all past posts from a certain category.

However, I want something a little more like what Problogger38 has done: a page that lets people discover additional content on my site in several different ways. That, again, is done with a page template.

Staying with our mixed template from before, we will add the following below the the_content() call:

<div class="archive-search-form"><?php get_search_form(); ?></div>

<h2>Archives by Year:</h2>
<ul><?php wp_get_archives('type=yearly'); ?></ul>

<h2>Archives by Month:</h2>
<ul><?php wp_get_archives('type=monthly'); ?></ul>
   
<h2>Archives by Subject:</h2>
<ul> <?php wp_list_categories('title_li='); ?></ul>

Plus, a little bit of styling for the search bar:

.archive-search-form {
  padding: 10px 0;
  text-align: center;
}

And the result should look a little bit like this:

The custom archive page.39
The custom archive page. (View large version40)

For completion’s sake, here is the entire file:

<?php
/**
 * Template Name: Custom archive template
 *
 */

get_header(); ?>

<div id="primary" class="site-content">
  <div id="content" role="main">

    <?php while ( have_posts() ) : the_post(); ?>
         
      <header class="entry-header">
        <?php the_post_thumbnail(); ?>
        <h1 class="entry-title"><?php the_title(); ?></h1>
      </header>

      <div class="entry-content">
        <?php the_content(); ?>
      
        <div class="archive-search-form"><?php get_search_form(); ?></div>

        <h2>Archives by Year:</h2>
        <ul><?php wp_get_archives('type=yearly'); ?></ul>

        <h2>Archives by Month:</h2>
        <ul><?php wp_get_archives('type=monthly'); ?></ul>
                
        <h2>Archives by Subject:</h2>
        <ul><?php wp_list_categories('title_li='); ?></ul>
      </div><!-- #entry-content -->

      <?php comments_template( '', true ); ?>               
    <?php endwhile; // end of the loop. ?>             
  </div><!-- #content -->
</div><!-- #primary -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

Don’t forget to assign it to a page!

WordPress Page Templates In A Nutshell

On your way to mastering WordPress, learning to use page templates is an important step. They can make customizing your website very, very easy and allow you to assign unique functionality and design to as many or few pages as you wish. From adding widget areas to showing custom post types to displaying a list of your website’s contributors — the possibilities are practically endless.

Whether you use conditional tags, exploit the WordPress template hierarchy, or create page-specific template files is entirely up to you and what you are trying to achieve. Start off small and work your way up to more complicated things. It won’t be long before every part of your WordPress website will answesr to your every call.

Do you have experience using page templates in WordPress? What other use cases can you add to the list? Any important details to add? Please tell us about it in the comments.

Image credit: Kevin Phillips41

(og, ml)

Footnotes

  1. 1 http://codex.wordpress.org
  2. 2 https://addons.mozilla.org/en-us/firefox/addon/firebug/
  3. 3 http://codex.wordpress.org/Template_Hierarchy#The_Template_Hierarchy_In_Detail
  4. 4 http://wphierarchy.com/
  5. 5 http://www.smashingmagazine.com/wp-content/uploads/2015/05/01-wp-template-hierarchy-opt.jpg
  6. 6 http://codex.wordpress.org/
  7. 7 http://www.smashingmagazine.com/wp-content/uploads/2015/05/01-wp-template-hierarchy-opt.jpg
  8. 8 http://codex.wordpress.org/Conditional_Tags
  9. 9 http://codex.wordpress.org/Conditional_Tags
  10. 10 http://www.themelab.com/ultimate-guide-wordpress-conditional-tags/
  11. 11 http://www.smashingmagazine.com/wp-content/uploads/2015/05/02-page-attributes-opt.jpg
  12. 12 http://www.smashingmagazine.com/wp-content/uploads/2015/05/02-page-attributes-opt.jpg
  13. 13 http://www.smashingmagazine.com/wp-content/uploads/2015/05/03-choose-page-template-manually-opt.jpg
  14. 14 http://www.smashingmagazine.com/wp-content/uploads/2015/05/03-choose-page-template-manually-opt.jpg
  15. 15 https://wordpress.org/plugins/what-the-file/
  16. 16 http://www.smashingmagazine.com/wp-content/uploads/2015/05/04-default-template-opt.jpg
  17. 17 http://www.smashingmagazine.com/wp-content/uploads/2015/05/04-default-template-opt.jpg
  18. 18 http://codex.wordpress.org/Page_Templates#Filenames
  19. 19 http://www.smashingmagazine.com/wp-content/uploads/2015/05/05-custom-wp-page-template-without-sidebar-opt.jpg
  20. 20 http://www.smashingmagazine.com/wp-content/uploads/2015/05/05-custom-wp-page-template-without-sidebar-opt.jpg
  21. 21 http://www.smashingmagazine.com/wp-content/uploads/2015/05/06-custom-full-width-wp-page-template-opt.jpg
  22. 22 http://www.smashingmagazine.com/wp-content/uploads/2015/05/06-custom-full-width-wp-page-template-opt.jpg
  23. 23 http://www.smashingmagazine.com/wp-content/uploads/2015/05/07-404-page-template-widgets-opt.jpg
  24. 24 http://www.smashingmagazine.com/wp-content/uploads/2015/05/07-404-page-template-widgets-opt.jpg
  25. 25 http://www.smashingmagazine.com/wp-content/uploads/2015/05/08-customized-404-error-page-via-template-opt.jpg
  26. 26 http://www.smashingmagazine.com/wp-content/uploads/2015/05/08-customized-404-error-page-via-template-opt.jpg
  27. 27 https://wordpress.org/plugins/types/
  28. 28 http://www.smashingmagazine.com/wp-content/uploads/2015/05/09-portfolio-page-without-custom-page-template-opt.jpg
  29. 29 http://www.smashingmagazine.com/wp-content/uploads/2015/05/09-portfolio-page-without-custom-page-template-opt.jpg
  30. 30 http://www.smashingmagazine.com/wp-content/uploads/2015/05/10-custom-portfolio-template-without-styling-opt.jpg
  31. 31 http://www.smashingmagazine.com/wp-content/uploads/2015/05/10-custom-portfolio-template-without-styling-opt.jpg
  32. 32 http://www.smashingmagazine.com/wp-content/uploads/2015/05/11-custom-portfolio-template-including-styling-opt.jpg
  33. 33 http://www.smashingmagazine.com/wp-content/uploads/2015/05/11-custom-portfolio-template-including-styling-opt.jpg
  34. 34 http://www.smashingmagazine.com/wp-content/uploads/2015/05/12-custom-contributor-page-opt.jpg
  35. 35 http://www.smashingmagazine.com/wp-content/uploads/2015/05/12-custom-contributor-page-opt.jpg
  36. 36 http://www.smashingmagazine.com/wp-content/uploads/2015/05/13-custom-contributor-page-without-styling-opt.jpg
  37. 37 http://www.smashingmagazine.com/wp-content/uploads/2015/05/13-custom-contributor-page-without-styling-opt.jpg
  38. 38 http://www.problogger.net/archives/
  39. 39 http://www.smashingmagazine.com/wp-content/uploads/2015/05/14-custom-archive-page-opt.jpg
  40. 40 http://www.smashingmagazine.com/wp-content/uploads/2015/05/14-custom-archive-page-opt.jpg
  41. 41 http://pixabay.com/en/users/kpgolfpro-27707/

The post A Detailed Guide To WordPress Custom Page Templates appeared first on Smashing Magazine.

Categories: Others Tags: