Sunday, March 22, 2009

Tip #4: Manipulating images at the command line

The popular ImageMagick package provides a rich set of tools for performing image manipulations at the command line. While a full description of all features is well beyond the scope of this tip series, a quick introduction is in order.

Users will likely find themselves primarily using the convert utility that comes with ImageMagick. Another utility, mogrify is similar to convert, with the exception that it overwrites input images rather than outputting to a new file. As such, convert is probably a safer choice, particularly when a user is new to ImageMagick.

The following command rotates an image clockwise by 90 degrees and scales it down by 85% in both dimensions:

linux@devbox:~/tip4> convert -rotate 90 -scale 85%x85% infile.png outfile.png


Here, the file infile.png is used as input, and the modified image is written to outfile.png. convert does not modify the input file.

We can also do file type conversions using convert. Here, a PostScript file is converted to a PNG file. Notice that the output filename is prefixed with png:. This explicitly instructs convert to convert the file to PNG format. In fact, this is generally unnecessary, as convert should infer this from the file extension specified for the output file.

linux@devbox:~/tip4> convert infile.ps png:outfile.png


We can also use convert as a filter by specifying - for either the input file or output file. In the former case, the input image is read from standard input. As you might expect, in the latter case, the output image is passed to standard output. The following demonstrates the use of convert as a filter by taking a PostScript file (infile.ps), converting it to a PNM file using pstopnm, converting the PNM file to a PNG file using pnmtopng, and passing the result to convert to be rotated and scaled. The resulting image is then saved to outfile.png. Of course, this example is contrived since we can directly use convert to convert an image from one format to another, but it helps to illustrate the use of convert as a filter.

linux@devbox:~/tip4>pstopnm -stdout infile.ps | pnmtopng | convert -rotate 90 -scale 85%x85% - outfile.png

No comments: