This simple script takes a source image, and up to two parameters to re-size the image using ImageMagick. This allows you to use a large source image that is suitable for a zoomed in view, and dynamically re-size it using the simple script which will make it fit the x,y constraints necessary for a site, and reduce the file size.
In testing the script, a sample PNG image with transparency was originally 500×500 pixels and 202.76kb in size. Using the script to set the x,y to 200×200 the file size was reduced to 44.73kb. The script could be easily extended to perform other ImageMagick functions, and to reduce the end result file size even more.
$img = strip_tags($_GET['imagename']);
$size = strip_tags($_GET['size']);
$size = 0;
$vsize = strip_tags($_GET['vsize']);
$vsize = 0;
$image = new Imagick($img);
Quick synopsis of the code: It first checks to make sure the imagick PHP extension is loaded, and if it is not, it will dynamically load the extension. It then checks for the URL parameter ‘imagename’ and runs a simple strip_tags to clean any extraneous attempts to send in other code with the image name. The script then does two checks for the size (horizontal) and vsize (vertical). If either is set, it will strip_tags on them and assign them to a variable for use.
The script then takes the sizes and instantiates a new Imagick object passing in the image name as set from the URL parameter. It then calls the thumbnailImage function of the Imagick library and passes in the $size and $vsize variables. We then set the header type to be image/png since we worked only with PNG images in this version, and finally print the results, which are contained in the $image object.
The nice thing about the script, is thumbnail image will take two parameters for the size, and if only one is set, it will auto-constrain the image (eg. 200, 0 it will autoscale the 0 axis). The other nice thing is we can check the type of image so that we output the same type so we can work with GIF, JPEG, and PNG among others.