You can read about two popular thumbnail generating methods in this article. The first method requires GD library. If you select the other way you need Imagick which is a native php extension to create and modify images using the ImageMagick API. Let's see the code!
First method: GD library
function gd_thumbnail($filename, $width = 200, $height = 200) {
$source = imageCreateFromString(file_get_contents($filename));
$x = imageSX($source);
$y = imageSY($source);
if ($x > $y) { // landscape orientation
$height = intval($y/($x/$width));
} else { // square or portrait orientation
$width = intval($x/($y/$height));
}
$destination = ImageCreateTrueColor($width, $height);
imageCopyResamled($destination, $source, 0, 0, 0, 0, $width, $height, $x, $y);
imagejpeg($destination, NULL, 92);
}
Second method: Imagick extension
function im_thumbnail($filename, $width = 200, $height = 200) {
$image = new Imagick($filename);
$image->thumbnailImage($width, $height, TRUE);
echo $image;
}
Usage
You can generate thumbnail image to visitor's browser:
header('Content-type: image/jpeg');
im_thumbnail('path/to/image.jpg'); // you can use gd_thumbnail() here
This code will response a JPEG image.
You can save thumbnail image to file:
$fileContent = gd_thumbnail('path/to/image.jpg'); // you can use im_thumbnail() here
file_put_contents('path/to/image_thumbnail.jpg', $fileContent); // save image
This is very easy, isn't it?
Have a nice day, and use these code as you need.