PHP Image Resize / Cropping classes?

Hey all,

I was wondering how facebook get images to display as a set width and height regardless of the dimension of the original photo? All album covers are 130 x 130 and focus on the centre of the photo (is this some form of cropping?) and I would like to know how this is achieved?

I am using a pretty cool PHP image resize class on my own site, but the methods available resize and image to a specific width, height, or width and height rather than centring in on an image and cropping it (hope that makes sense).

thanks for any tips!

You can use the GD Libraries imagecopy() functions for this. There are several to choose from, but for resizing and cropping, you should use [URL=“”]imagecopyresampled() to maintain quality.

What you’ll want to do is determine the aspect ratio of your final image, and the determine which boundary that aspect collides with first. For demonstrative purposes, let’s say you want a 16:9 picture cropped from a 4:3 image.

Original Dimensions: 800x600
Target Dimensions: 320x180

Divide the original dimensions by the targets:
Ratios: 2.5 x 3.333
The width ratio is smaller, so it hits the bounding box first, and is our starting width.

Now divide the second dimension (in this case, the height) by its ratio and multiply by the ratio from the first.

Height = (600 / 3.333) * 2.5 = 450

The height and width you now want to copy is 800x450.
To center it, get the height of the image, subtract the cropping height, and divide by 2 to get the y offset.

(600 - 450)/2 = 75

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  );

//With our information, this would be as follows:
imagecopyresampled  (resource $dst_image,  resource $src_image,  0,  0,  0,  75,  320,  180,  800,  450);

Of course, you’ll be doing this with variables:

imagecopyresampled (
resource $dst_image, resource $src_image,  
0,  0,  
[x offset in source. Used if height hits boundary, otherwise 0],  [y offset in source. Used if width hits boundary, otherwise 0],  
[target image width],  [target image height],  
[calculated width of crop],  [calculated height of crop])

I hope this helps!

That was a truley outstanding post, very helpful and informative, thanks!! :slight_smile: