Create thumbnail
-Image processing in PHP
Before you start this lesson, before read the lesson PHP
Image processing introduction and make sure you enable GD library.
Here is PHP code to create an thumbnail for an image.
<?php
// Import the image to use
$src_img = imagecreatefromjpeg("pig.jpg");
$width = imagesx($src_img); // get original source image
width
$height = imagesy($src_img); // and height
// create small thumbnail
$dest_width = 80;
$dest_height = 60;
$dest_img = imagecreatetruecolor($dest_width, $dest_height);
imagecopyresized(
$dest_img, $src_img,
0, 0, 0, 0,
$dest_width, $dest_height,
$width, $height); // resize the image
imagepng($dest_img); // As though output to browser.
?> |
First, we get a source image by using function imagecreatefromjpeg().
We could get image from .gif,png, by using imagecreatefromgif(), imagecreatefrompng()
similarly.
Second, we create an black destination image,size 80 * 60,
by using imagecreatetruecolor() which will hold the thumbnail.
Third, resize the source image to 80 *60 and copy the resized
image to destination image.
Then, imagepng($dest_img) output to browser.
Thumbnail sample
We still used the lovely pig image used in Add
text on Image.
This is the original image.
This is its thumbnail
You may use the above code to create thumbnails for your image gallery. |