|Published (Last):||22 March 2011|
|PDF File Size:||2.51 Mb|
|ePub File Size:||2.49 Mb|
|Price:||Free* [*Free Regsitration Required]|
Dave Newton is a web developer in Toronto, Canada, and will soon be starting a new role as a front-end deveveloper at Shopify. He strongly believes in making … More about Dave Newton …. Every second Tuesday, we send a newsletter with useful techniques on front-end and UX. 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.
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. The average web page is about 2 MB 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.
Improving web performance and giving a better experience to our users is our job as developers and designers. Responsive images to the rescue!
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. This is where automated image resizing comes in handy. A bunch of tools out there do this, including GD and GraphicsMagick , but ImageMagick 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 WordPress and Drupal , integrated with task runners such as Grunt , and used on its own to automate image editing — including resizing. If you use Homebrew on a Mac, you can install it like this:. Otherwise, look for it in your favorite package manager, or download it directly from the ImageMagick website. 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. 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.
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. Those pixels will need some color value, and the process of determining that color value is called interpolation.
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.
Background interpolation is only possible when adding pixels i. 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. Downsampling i. 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.
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.
For anything more complicated than a line or square, nearest-neighbor interpolation produces very jagged, blocky images. 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. 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. 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. ImageMagick has a ton of options and functions , 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.
Each function uses the same format: -functionName option. As before, this resizes input. The lower the score, the more the images resemble each other; a score of zero means they are identical. I also tested at three output sizes , and pixels wide from a variety of input sizes. Finally, I tested both with and without image optimization. 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.
Choosing a resampling filter in ImageMagick is surprisingly complicated. There are three ways you can do this:. 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:.
This means that if we were resizing an image to be pixels wide, -thumbnail would first resize it to 2, 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, pixels wide to 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. 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.
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. Unsharp filters work by first applying a Gaussian blur 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.
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.
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 s rock posters , with a few discrete bands of color. 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. Unfortunately, ImageMagick has a bug that ruins images with transparency when dithering is used like this. Luckily, even without dithering, the posterized images still look good. The color space defines what colors are available for an image. All of these contain fewer colors than are visible to the human eye.
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. 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.
It turns out that JPEG quality scales are not defined in a specification or standard, and they are not uniform across encoders.
For non-lossy image formats , such as PNG, quality and compression are not related at all. PNG compression in ImageMagick can be configured with three settings, -define png:compression-filter , -define png:compression-level and -define png:compression-strategy. 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. Neither of these should affect quality at all. Sequential rendering is usually the default: The image will load pixels row by row from top to bottom.
Efficient Image Resizing With ImageMagick
TIL: The Best Way to Compress JPG Files with ImageMagick
Dave Newton is a web developer in Toronto, Canada, and will soon be starting a new role as a front-end deveveloper at Shopify. He strongly believes in making … More about Dave Newton …. Every second Tuesday, we send a newsletter with useful techniques on front-end and UX. 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. 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.