GD: Cropping with ImageCopyResampled

Hey everyone,

I’m relatively new to PHP, and I’m trying to resize an image and crop it down to 2x3 using ImageCopyResampled.

Here’s the code I’m using:

$wh_ratio = $width / $height;
	if ($wh_ratio > 3 / 2) {
		// Crop horizontal
		$crop_h = ($width - ($height * 3 / 2)) / 2;
		$crop_v = 0;
	}
	elseif ($wh_ratio < 3 / 2) {
		// Crop vetical
		$crop_h = 0;
		$crop_v = ($height - ($width * 2 / 3)) / 2;
	}
	else {
		// No crop
		$crop_h = 0;
		$crop_v = 0;
	}
	// Create thumbnail
	$source = $function ($tmp_name);
	$destination_thumb = imagecreatetruecolor (143, 95);
	imagecopyresampled ($destination_thumb, $source, 0, 0, $crop_h, $crop_v, 143, 95, $width, $height);
	imagejpeg ($destination_thumb, $images_dir.'/thumbs/'.$new_name, 100) or $error = 'The thumbnail was not saved to the server.';
	// Free the memory
	imagedestroy ($source);
	imagedestroy ($destination_thumb);

The resizing is working fine, but without cropping it distorts the image. When I use the code above it seems to reposition the distorted image $crop_h/$crop_v pixels, rather than cutting off $crop_h/$crop_v pixels on both sides.

Am I using this wrong? How could I get the desired effect? Thanks in advance for any ideas. -Matt

Edit: I attached photos showing the problem… the first one is uncropped and distorted, the second one is using the code above.

bump

Don’t forget to decrease the width and height as you do the coordinates:


imagecopyresampled ($destination_thumb, $source, 0, 0, $crop_h, $crop_v, 143, 95, $width-2*$crop_h, $height-2*$crop_v);

beautiful. it works perfectly.

I’m voting for you in the sitepoint awards!

Glad it worked and thanks :smiley: