Resizing Images to Generate Thumbnails in PHP

Warning! Some information on this page is older than 5 years now. I keep it for reference, but it probably doesn't reflect my current knowledge and beliefs.

# Resizing Images to Generate Thumbnails in PHP

Jan 2012

Some time ago I came across a problem of calculating an image size for automatically generated thumbnail for gallery script coded in PHP. It required a moment's thought, so I'd like to share this algorithm. In fact there will be two algorithms.

First code scales the image down with following rules: Destination size will not exceed given thumbnail size, but the width or height can be smaller to always preserve aspect ratio. Images smaller than thumbnail size are not magnified.

$src_size_x, $src_size_y - Source image size.
THUMBNAIL_SIZE_X, THUMBNAIL_SIZE_Y - Constants defining thumbnail size.

$dst_size_x, $dst_size_y - Destination thumbnail size.

if( $src_size_x <= THUMBNAIL_SIZE_X && $src_size_y <= THUMBNAIL_SIZE_Y )
  $dst_size_x = $src_size_x;
  $dst_size_y = $src_size_y;
  $dst_size_x = THUMBNAIL_SIZE_X;
  $dst_size_y = (int)( $src_size_y * THUMBNAIL_SIZE_X / $src_size_x );
  if( $dst_size_y > THUMBNAIL_SIZE_Y )
    $dst_size_x = (int)( $src_size_x * THUMBNAIL_SIZE_Y / $src_size_y );
    $dst_size_y = THUMBNAIL_SIZE_Y;

Second algorithm also helps with generating image thumbnails, but works differently. It assumes that destination image will always be of size (THUMBNAIL_SIZE_X, THUMBNAIL_SIZE_Y), while source iamge can be cropped to select only the center of the image if it has different aspect ratio than the thumbnail.

Inputs to this algorithm are the same, while outputs are:

$src_x, $src_y - Offset in the source image to begin copying from.
$src_w, $src_h - Size of the rectangle to select from cropped source image.

The code that uses this algorithm should then select from the source image a rectangle with left-top position ($src_x, $src_y), size ($src_w, $src_h) and copy it, with scaling and resampling, to the destination image with the size exactly (THUMBNAIL_SIZE_X, THUMBNAIL_SIZE_Y). That's what imagecopyresampled function from GD library can do. This algorithm does not handle cases where source image is smaller than thumbnail.

$src_h = $src_size_y;
$src_w = (int)( $src_h * THUMBNAIL_SIZE_X / THUMBNAIL_SIZE_Y );

if( $src_w <= $src_size_x )
  $src_x = ( $src_size_x - $src_w ) / 2;
  $src_y = 0;
  $src_w = $src_size_x;
  $src_h = (int)( $src_w * THUMBNAIL_SIZE_Y / THUMBNAIL_SIZE_X );
  $src_x = 0;
  $src_y = ( $src_size_y - $src_h ) / 2;

Comments | #webdev #algorithms #php Share


[Stat] [STAT NO AD] [Download] [Dropbox] [pub] [Mirror]
Copyright © 2004-2017