Thumbnails of images with PHP center

Create tracks: Third part

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

However, images still have the disadvantage of being cropped on the right or bottom, but it would be better to center the thumbnail by cropping on both sides at the same time. In addition, the script only processes images in jpg format, and it should be extended to other graphic formats common on the Web: gif and png.

Centering the thumbnail

Two offset variables are added:

$xoff = 0;
$yoff = 0;

Offset - The difference between the height of the intermediate image and the height of the end thumbnail or width .

If the height is to be trimmed, this row is added to the script to calculate the vertical offset:

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

and if it is width:

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

These offsets are then inserted into the parameter of a function that records part of the intermediate image:

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

Handling different graphics formats

The table contains the main formats recognized by PHP, associating the image code with the file extension:

$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 pathinfo function arrays the components of the file path, among which you can find the extension.

Depending on the returned type code, the image reading function is selected:

$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 Script

The archive contains a PHP script and images from the gallery below .

Art Gallery