25
Aug '12

Creating Thumbnails in PHP

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.

Leave a Reply