Centered Thumbnails in PHP

Building Thumbnails: Third Part

In the first part of this tutorial we saw how to create thumbnail images
The script was developed in the second part to achieve galleries of thumbnail of same size.

However, the images are the drawback to be cropped on the right side or on the bottom, but it would be better to center the image by cropping on both sides at once. In addition, the script deals only with images in jpg format, and it should be extended to other graphic formats common on the Web: gif and png.

Centering the thumbnail

Two variables are added for offsets:

$xoff = 0;
$yoff = 0;

The offset is the difference between the height of the intermediate image and height of the final thumbnail, or width.

When the height must be cropped, the followings line is added to the script to calculate the vertical offset:

$yoff = intval(($nh - $thumbh) / 2); 

and if this is the width:

$xoff = intval(($nw - $thumbw) / 2);

then these offsets are incorporates as parameter of the function that copies a part of the intermediate image:

imagecopy($viewimage, $newimage, 0, 0, $xoff, $yoff, $nw, $nh);

Handling different graphics formats

An array contains the main graphics formats recognized by PHP, allowing to associate the extension to a code of format:

$types = array("jpeg"=>IMG_JPG, "jpg"=>IMG_JPG, "gif"=>IMG_GIF, "png"=>IMG_PNG );

function getImageType($name)
{
  global $types;
  
  $way = pathinfo($name);
  $ext = strtolower($way['extension']);
  $t = $types[$ext];
  return $t;  
}

The PHP function pathinfo returns in an array components of a file path, including the extension.

Depending on the code of format returned, different functions are used to load the image:

$t = getImageType($oldname); 

switch($t)
{
    case IMG_JPG: $resimage = imagecreatefromjpeg($oldname);
                  break;
    case IMG_GIF: $resimage = imagecreatefromgif($oldname);
                  break;
    case IMG_PNG: $resimage = imagecreatefrompng($oldname);
                  break;                  
}  

Download the script

The archive contains the PHP script and images of the gallery below.

Thumbnail gallery