All of these examples use the PHP simple image manipulation class that I created.
Every now and then I write a batch image converter snippet that others might find useful. I figure I’ll post them here for my benefit and yours. These snippets will also serve as a way to better understand the class. As I come up with these in life, I’ll update this post.
All of these examples assume that you’ve already included the class in your file.
Resize and Crop Directory of Images to Generate Usable Thumbnails
This snippet will take a $dir path and process all the images in that directory. It will first resize the image to 50% of its original dimensions, it will then crop 60 pixels from every side. The result is a little smaller than the original, and still displays the content of the image at a size that is easy to understand what’s going on in the image.
Why? I’m redesigning a website and have a bunch of “full sized” images of marble stone in JPG that were either blown up at some point or saved in very low quality… so they are a bit artifacty. I needed to generate thumbnails of all these textures, and creating a thumbnail of these poor quality images resulted in even crappier thumbnails. My solution was to first reduce the size of the full image by half to make it look a little crisper. Then, instead of simple resizing the file to generate a thumbnail, I cropped the edges, so that you could still see the texture of the marble. The result is a resize for clarity, and a crop for usability.
$dir = './images';
$d = dir($dir);
while ( $entry = $d->read() )
{
$f = $dir.'/'.$entry;
if ( is_dir($f) ) continue;
// load the image
$I = new Image($f);
// resize the image to make it look a little nicer, this will also allow our thumbnail to display more of the image
$I->resize('50%');
// crop off the edges to make it fit our target dimensions instead of simply resizing to our target dimensions
// this has the benefit of allowing the image to still be recognizable and show detail
// have you ever tried to recognize a face in a picture that has been resized? this method solves that
$I->crop_all(60);
// since we are creating thumbnails, we want to save to a new location instead of using the $I->save method
// which would overwrite our original
// in the example below, we use a shortocut to make our filenames conform filename-sm.jpg
$I->write( $dir.'/'.str_replace('.', '-sm.', $entry) );
// clear memory, PHP shouldn't leak, but you never know, I just unset (in PHP 5 you might also need to do a $I->__destroy() first)
unset($I);
}
$d->close();
