Create image thumbnail with PHP
A guide on how to create an image thumbnail with PHP using the GD library. This PHP code helps resize an original image to a custom thumbnail size.
<?php
function createThumbnail($source_image_path, $thumbnail_path, $thumb_width) {
// Get original image info
list($width, $height, $image_type) = getimagesize($source_image_path);
// Calculate thumbnail dimensions
$thumb_height = intval($height * $thumb_width / $width);
// Create a blank thumbnail
$thumbnail = imagecreatetruecolor($thumb_width, $thumb_height);
// Create image from source file
switch ($image_type) {
case IMAGETYPE_GIF:
$source_image = imagecreatefromgif($source_image_path);
break;
case IMAGETYPE_JPEG:
$source_image = imagecreatefromjpeg($source_image_path);
break;
case IMAGETYPE_PNG:
$source_image = imagecreatefrompng($source_image_path);
break;
default:
return false;
}
// Resize the source image into the thumbnail
imagecopyresampled($thumbnail, $source_image, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height);
// Save the thumbnail
switch ($image_type) {
case IMAGETYPE_GIF:
imagegif($thumbnail, $thumbnail_path);
break;
case IMAGETYPE_JPEG:
imagejpeg($thumbnail, $thumbnail_path, 90); // Quality 90%
break;
case IMAGETYPE_PNG:
imagepng($thumbnail, $thumbnail_path);
break;
}
// Free up memory
imagedestroy($source_image);
imagedestroy($thumbnail);
return true;
}
// Use the function to create a thumbnail
$source_image = 'source_image.jpg';
$thumbnail_image = 'thumbnail_image.jpg';
$thumbnail_width = 150;
if (createThumbnail($source_image, $thumbnail_image, $thumbnail_width)) {
echo "Thumbnail created successfully!";
} else {
echo "Failed to create thumbnail.";
}
?>
Detailed explanation:
-
Get original image info:
getimagesize($source_image_path)
: Retrieves the dimensions and type of the original image.
-
Calculate thumbnail dimensions:
$thumb_height = intval($height * $thumb_width / $width)
: Calculates the height for the thumbnail, maintaining the aspect ratio of the original image.
-
Create a blank thumbnail:
imagecreatetruecolor($thumb_width, $thumb_height)
: Creates a blank canvas for the thumbnail.
-
Create image from source file:
- Use
imagecreatefromgif
,imagecreatefromjpeg
, andimagecreatefrompng
to generate an image resource based on the image type (GIF, JPEG, PNG).
- Use
-
Resize the source image into the thumbnail:
imagecopyresampled()
: Resizes the source image into the thumbnail, preserving quality.
-
Save the thumbnail:
- Save the thumbnail in the same format as the original image using
imagegif
,imagejpeg
, orimagepng
.
- Save the thumbnail in the same format as the original image using
-
Free up memory:
imagedestroy()
: Frees the memory associated with the image resources to avoid memory leaks.
-
Use the function:
- Executes the function to create the thumbnail from the original image and saves it as a new file.
PHP Version:
This code can run on PHP versions from 5.0 and above, requiring the GD extension for image processing.