Efficient Image Resizing With ImageMagick

I want to read this blog article because I want to find out the best way to determine an appropriate background color when extending an image with imagemagick.

Date Created:
1 49

References



Related


  • Image Upsampling
    • Making images larger. Increasing the number of pixels in an image.
  • Image Resampling
    • Taking an image and applying it to a new pixel grid. The process of altering an image's resolution by either adding or removing extra filters.

Image Resampling

  • Interpolation
    • A type of estimation, a method of constructing (finding) new data points based on the range of a discrete set of known data points. The process of determining color values for new pixels during image resampling is called interpolation.
  • Resampling Filter
    • A resampling filter is a type of algorithm used to change the number of pixels in an image.
  • Background Interpolation
    • Adding pixels in some arbitrary color.
  • Nearest Neighbor Interpolation
    • Making new pixels the same color as their neighboring pixels. This is also sometimes called point sampling.
  • Structural Similarity
    • The structural similarity index measure (SSIM) is a method for predicting the perceived quality of digital television and cinematic pictures, as well as other kinds of digital images and videos. It's also used for measuring the similarity between two images. The SSIM index is a full reference metric; in other words, the measurement or prediction of image quality is based on an initial understanding on an initial uncompressed or distortion-free image as reference.
  • Gaussian Blur
    • In image processing, a gaussian blur (sometimes called Gaussian smoothing) is the result of blurring an image by a Gaussian function. It's widely used in graphics software, typically to reduce image noise and reduce detail. The visual effect of this blurring technique is a smooth blur resembling that of viewing the image through a translucent screen. Gaussian smoothing is also used as a pre-processing stage in computer vision algorithms in order to enhance image structures at different scales.
  • Posterization
    • Posterization or posterisation of an image is the conversion of a continuous gradation of tone to several regions of fewer tones, causing abrupt changes from one tone to another.

Gaussian Blur Example

  • Dithering
    • Dither is an intentionally applied form of noise used to randomize quantization error, prevent large-scale patterns such as color banding in images. Dither is routinely used in processing of both digital audio and video data, and is often one of the last stages of mastering audio to a CD.

Dithering Example


  • Color Space
    • A color space is a specific organization of colors. In combination with color profiling supported by various physical devices, it supports reproducible representations of color - whether such representation entails analog or a digital representation. A color space may be arbitrary or of structured mathematical rigor. A color space is a useful conceptual tool for understanding the color capacities of a particular device or digital file.


Notes


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. This blog article discusses using ImageMagick - an open source command-line graphics editor - to quickly resize your images, while maintaining great visual quality and really tiny file sizes.

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.

Nearest neighbor interpolation often provides much better results than background interpolation. 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.

In order to make outputted images smaller, we'll need to look at ways to reduce the number of colors without sacrificing quality.

In research released last yearRadWare found that image pairs with a DSSIM score of 0.015 were indistinguishable to their test users.

There are three ways you can choose a resampling filter in ImageMagick:

  1. with the resizing function you choose
  2. with the --filter option
  3. with the --interpolate setting

Resizing Function

The -resize function creates files that are too large. The -thumbnail function does a better job of optimizing quality and file size. The -thumbnail function uses a three step process to resize images:

  1. Resizes an 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.
  2. It resizes the image to its final output size using the basic -resize filter.
  3. It strips metadata from the image.

Filter Option

Some resining functions (such as -sample) have a built-in resampling function that's always used, but others have defaults that can be overwritten with -filter. The -filter setting gets used in -thumbnail's second step, because that step uses -resize.

The best filter option according to this article is the Triangle resampling filter. This filter uses bilinear interpolation; it determines pixel area by looking at support area of neighboring pixels and produces a weighted average of their colors. The best way to specify this support area at two pixels is by using the -define filter:support=2 setting.

In addition to the settings above, by default ImageMagick also uses something called JPEG fancy upsampling, 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 often get a little blurry when resized, so this author recommends 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 blur to the image. The first two values to the unsharp filter are the radius and sigma. These values combines 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).

Color Reduction

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, greed, and blue color channels that images use. 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.

It's best to turn dithering off with -dither None in ImageMagick.

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. 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.

Color Space

Quality and Compression

With lossy image formats, quality and compression go hand in hand: the higher the compression, the lower the quality and lower the file size. This blog post recommends a -quality 82 setting. 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.

PNG compression in ImageMagick can be configured with three settings, -define png:compression-filter, define png:compression-level, and define png:compression-strategy. Compression filtering is a pre-compression step that reorganizes the image's data so that the actual compression is more efficient. This blog recommends using adaptive filtering (-define png: compression-filter=5). Compression level is the amount of compression that gets applied; it is recommended to max this out at 9 (-define png:compression-level=9). The compression strategy setting determines the actual algorithm that's used to compress the files; it is recommended to use the default compression strategy (-define png:compression-strategy=1).

Metadata

-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.

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 by row from top to bottom. Progressive rendering increases the file size.

Progressive Rendering

The recommended settings in this article so far can decrease file size by about 25%.

$ mogrify -path <input_file> -filter Triangle -define filter:support=2 -thumbnail <output_file> -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 <output_directory>

Comments

You have to be logged in to add a comment

User Comments

Frank Frank

Test of the comment functionality

Kangaroo

1

Insert Math Markup

ESC
About Inserting Math Content
Display Style:

Embed News Content

ESC
About Embedding News Content

Embed Youtube Video

ESC
Embedding Youtube Videos

Embed TikTok Video

ESC
Embedding TikTok Videos

Embed X Post

ESC
Embedding X Posts

Embed Instagram Post

ESC
Embedding Instagram Posts

Insert Details Element

ESC

Example Output:

Summary Title
You will be able to insert content here after confirming the title of the <details> element.

Insert Table

ESC
Customization
Align:
Preview:

Insert Horizontal Rule

#000000

Preview:


View Content At Different Sizes

ESC

Edit Style of Block Nodes

ESC

Edit the background color, default text color, margin, padding, and border of block nodes. Editable block nodes include paragraphs, headers, and lists.

#ffffff
#000000

Edit Selected Cells

Change the background color, vertical align, and borders of the cells in the current selection.

#ffffff
Vertical Align:
Border
#000000
Border Style:

Edit Table

ESC
Customization:
Align:

Upload Lexical State

ESC

Upload a .lexical file. If the file type matches the type of the current editor, then a preview will be shown below the file input.

Upload 3D Object

ESC

Upload Jupyter Notebook

ESC

Upload a Jupyter notebook and embed the resulting HTML in the text editor.

Insert Custom HTML

ESC

Edit Image Background Color

ESC
#ffffff

Insert Columns Layout

ESC
Column Type:

Select Code Language

ESC
Select Coding Language

Insert Chart

ESC

Use the search box below

Upload Previous Version of Article State

ESC