Resizing some images to same width

Jurjen Bokma

May 2010

For a slideshow on a webpage, we want to resize all the images to the same width. (Ideally they should also have the same height, but we don't want to alter the aspect ratio.)

  1. In this case, they were on a webpage already, and I downloaded them from there. There were only six, so no need for fancy wget scripts...

    user@host:~$ ls -trl
    total 532
    -rw-r--r-- 1 jurjen jurjen  30889 2010-05-24 19:32 201005231646598954.JPG
    -rw-r--r-- 1 jurjen jurjen 103113 2010-05-24 19:32 201005231647005694.JPG
    -rw-r--r-- 1 jurjen jurjen  76754 2010-05-24 19:32 201005231647003931.JPG
    -rw-r--r-- 1 jurjen jurjen  82611 2010-05-24 19:32 201005231647004694.JPG
    -rw-r--r-- 1 jurjen jurjen  75823 2010-05-24 19:32 201005231656225675.jpg
    -rw-r--r-- 1 jurjen jurjen 161098 2010-05-24 19:32 201005231656224154.JPG

  2. Enlarging pictures is tricky with jpeg, so we want to reduce all the images to the width of the smallest.

    user@host:~$ identify -format "%g\n" ./*

    From this output, it is easy to figure out the smallest width (418). For longer lists of files, we could grep -o ^[0-9]* or awk -Fx '{print $1"' the first number out and pipe the list through sort and head...

  3. We use this four-line script:

    for F in $(ls -1) ; do
    X=$(identify -format "%g" ${F}|cut -d 'x' -f 1)
    convert -resize $((41800 / ${X}))% ${F} ${F}.converted
    mv ${F}.converted ${F}

    ... and we list the output:

    user@host:~$ identify *
    201005231646598954.JPG.converted JPEG 418x485 418x485+0+0 DirectClass 8-bit 29.5879kb
    201005231647003931.JPG.converted[1] JPEG 415x311 415x311+0+0 DirectClass 8-bit 50.0234kb
    201005231647004694.JPG.converted[2] JPEG 417x337 417x337+0+0 DirectClass 8-bit 52.416kb
    201005231647005694.JPG.converted[3] JPEG 416x327 416x327+0+0 DirectClass 8-bit 50.666kb 0.020u 0:02
    201005231656224154.JPG.converted[4] JPEG 416x332 416x332+0+0 DirectClass 8-bit 47.2891kb
    201005231656225675.jpg.converted[5] JPEG 410x307 410x307+0+0 DirectClass 8-bit 22.3496kb