Mogrify to the Rescue
is one of the programs included in the extremely powerful
manipulation suite. It is capable of changing colors, sizes, formats, and
effects of an image in any of dozens of common formats. It was the perfect
tool for this job.
The first step, after actually uploading the original image to the server,
is to determine its current dimensions:
$currentimagesize = getimagesize($UPLOADS_URL . $imagename);
This returns an array of information about the image. In this case, we're
interested in the height and width.
$UPLOADS_URL is a global
variable we set which simply points at the location of the uploaded original
$image_width = $currentimagesize;
To resize the image, while retaining its original proportions, we need to
determine the current dimensions and then calculate the new desired size
(based on our maximum acceptable size of 200 pixels by 200 pixels).
if (($image_height > $max) || ($image_width > $max))
if ($image_height > $image_width)
$sizefactor = (double) ($max / $image_height);
$sizefactor = (double) ($max / $image_width) ;
$newwidth = (int) ($image_width * $sizefactor);
$newheight = (int) ($image_height * $sizefactor);
In other words, if our uploaded image is 800 pixels wide by 200 pixels tall,
$sizefactor is 0.25 (200/800), and both dimensions are
multiplied by this number to get a new image size of 200 pixels wide by
50 pixels high. The only thing left to do is the resizing itself:
$newsize = $newwidth . "x" . $newheight;
$cmd = "/usr/X11R6/bin/mogrify -resize $newsize ".
exec($cmd, $exec_output, $exec_retval);
if($exec_retval > 0)
print "ERROR: exec() error: $exec_output";
print "Image was resized from " . $image_width . "x" .
$image_height . " to $newsize :)";
Note that that path to mogrify on your server will probably be different than
the one on the Modwest.com server (/usr/X11R6/bin/mogrify). Also note that
we redirect STDERR to STDOUT (2>&1) in the exec() line. This assures that
we catch any error or warning message generated during the resizing process.
Having resized the image, all that remains is to insert it into a database or
move it to the appropriate location.
Thanks to ImageMagick's mogrify program, a little bit of PHP code has
prevented our client from slapping a huge image on the front page of their
site, while requiring no technical graphic manipulation or other additional
work on the part of their non-technical staff.