There are many websites accepting user’s photos and many of them want very small images. They always specify maximum file size. But many programs designed to help in such problems support only choosing image’s dimensions. So I wrote a Bourne shell script which could help with this.
There is a simple reason why we can’t simply predict appropriate image dimensions – usually the files are compressed. I’ve written previously about using PNG or JPEG on the Web and that files in these formats usually can be made smaller without any visible changes. Therefore, a program should determine appropriate dimensions, knowing how large the output file might be.
My shell script uses binary search to determine the dimensions of the image. It tries to scale a image to an integer percentage of the original size, starting with the original size, then with its half, recursing then in the half in which the optimal size lay, i.e. which has the largest dimensions with file size less than or equal to the specified value. For an image scaled to 17% of its original size it tried 9 scales, when without binary search it would test 100 cases (it would be nice if post offices used this method to find letters).
Like many other shell scripts, this one was designed to be simple. It uses ImageMagick to convert the images between any supported by it file formats and to scale them. If the output file name suggests that it is a PNG or JPEG, then appropriate program is used to make the file smaller without changing its appearance. For JPEGs comments and EXIF date are removed, since in my opinion they are not used by services requesting such small files.
The simplicity of it also leads to some possible problems with the script. Since it does not detect if the input and output files have the same format, even unscaled files are passed through ImageMagick. For JPEGs this may decrease quality. For one of KDE’s wallpapers it even increased file size by 10 KiB (not a real problem since I asked it to make a file smaller than a much large size). The binary search algorithm assumes that the list of output files with increasing dimensions is increasing, I’m not sure if this is true if any compression is used.
The script is licensed under the GNU General Public License, version 3 or later. It is available in my Mercurial repository. I tested it on Gentoo GNU/Linux with the dash shell.
