Search code examples
unixgnu-makenetpbm

How to use pnmscale to scale the longer side of an image and still keep the ratio?


I'm writing a GNU Makefile to do some processing on images. One task is to scale the image (.ppm format) by a SIZE parameter using the pnmscale command. The image should be scaled by the longer side without loosing the ratio and should be saved under .scaled .

I've read the man page of pnmscale but couldn't seem to find the right option.

I've tried the following:

pnmscale -pixels 100 example.ppm > example.scaled

When example.ppm has the size 200 x 100 pixels and I run the pnmscale command with the size of 100 pixels, example.scaled should have the size of 100 x 50 pixels. With my solution the image gets very small.


Solution

  • As the manpage of pnmscale states, the option pixels

    specifies a maximum total number of output pixels. pnmscale scales the image down to that number of pixels. If the input image is already no more than that many pixels, pnmscale just copies it as output; pnmscale does not scale up with -pixels.

    In other words, by specifying -pixels 100, you're actually scaling down your image to a maximum number of 100 pixels. What you're trying to achieve is to scale down your input image to a size of 100 x 50 pixels = 5000 pixels.

    Looking again at the manpage of pnmscale yields the following:

    pnmscale [{-xsize=cols | -width=cols | -xscale=factor}] [{-ysize=rows | -height=rows | -yscale=factor}] [pnmfile]
    

    [...]

    If you specify one dimension as a pixel size and don't specify the other dimension, pnmscale scales the unspecified dimension to preserve the aspect ratio.

    In your case, using

    pnmscale -xsize 100 example.ppm > example.scaled
    

    should shrink your input image to a width of 100 pixels.