John Main Logo

John Main

Code. Design. Hosting. Maintenance.

Aug '12

Creating thumbnails is actually fairly simple in PHP, for a simple scale/stretch you can do the following:

$image_path = '/path/to/image';
$thumbnail_path = '/path/to/thumbnail';
$thumbnail_width = 100;
$thumbnail_height = 100;
$thumbnail_quality = 60;
$image = imagecreatefromjpeg($image_path);
$imagex = imagesx($image);
$imagey = imagesy($image);
$thumbnail_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
imagecopyresampled($thumbnail_image, $image, 0, 0, 0, 0, $thumbnail_width, $thumbnail_height, $imagex, $imagey);
imagejpeg($thumbnail_image, $thumbnail_path, $thumbnail_quality)

Bearing in mind that this is setup for jpegs only. For other file formats PHP has corresponding functions – imagecreatefrompng, imagepng, imagecreatefromgif, imagegif etc

Also if you don’t provide a thumbnail path to the imagejpeg function then the image will be rendered directly, allowing you to have dynamically generated thumbnails.

Aug '12

Having struggles with the limitations of PHP’s scandir in the past, I was delighted to discover DirectoryIterator. It traverses through a directory just as scandir does but for each file or subfolder it finds, you get an object that provides easy access to all the properties of the file. It is also very very simple to implement:

foreach (DirectoryIterator($directory) as $file_or_folder) {
if ($file_or_folder->isFile()) {
//do something
elseif($file_or_folder->getExtension() == 'jpg') {
//do something else