How to Create Image Thumbnails

Image thumbnails are basically a smaller size copy of a larger image. They can be created using PHP GD Library functions alongside a file system function that we already learned about.

The getimagesize() file function will return the dimensions of the image specified. It can be used together with the list() function to minimize code and effort.

The imagecopyresampled() function can be used to stick a smaller version of an existing image into a new (smaller) image, thus creating a thumbnail.

The syntax is: imagecopyresampled(resource $dst_image, resource $src_image, int $dst_x, int $dst_y, int $src_x, int $src_y, int $dst_w, int $dst_h, int $src_w, int $src_h)

  • dst_image = Destination Image
  • src_image = Source Image
  • dst_x = X Coordinate of Destination Image
  • dst_y = Y Coordinate of Destination Image
  • src_x = X Coordinate of Source Image
  • src_y = Y Coordinate of Source Image
  • dst_w = Destination Width
  • dst_h = Destination Height
  • src_w = Source Width
  • src_h = Source Height

Putting it together, the script will look like this:

<?php
header('Content-type: image/jpeg');
$file = 'sky.jpg';

$new_width = 150;
$new_height = 150;
list($old_width, $old_height) = getimagesize($file);

$new_image = imagecreatetruecolor($new_width, $new_height);
$old_image = imagecreatefromjpeg($file);

imagecopyresampled($new_image, $old_image, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height);

imagejpeg($new_image);
imagedestroy($old_image);
imagedestroy($new_image);
?>

 

Summary:

Function Description
imagecopyresampled() Copy & Resize Part of An Image With Resampling

Comments