tags:

views:

430

answers:

1
+1  Q: 

Crop image in PHP

Hello,

The code below crops the image well, which is what i want, but for larger images, it wotn work as well. Is there any way of 'zooming out of the image'

Idealy i would be able to have each image roughly the same size before cropping so that i would get good results each time

Code is

<?php

$image = $_GET['src']; // the image to crop
$dest_image = 'images/cropped_whatever.jpg'; // make sure the directory is writeable

$img = imagecreatetruecolor('200','150');
$org_img = imagecreatefromjpeg($image);
$ims = getimagesize($image);
imagecopy($img,$org_img, 0, 0, 20, 20, 200, 150);
imagejpeg($img,$dest_image,90);
imagedestroy($img);
echo '<img src="'.$dest_image.'" ><p>';

?>

+4  A: 

If you are trying to generate thumbnails, you must first resize the image using imagecopyresampled();. You must resize the image so that the size of the smaller side of the image is equal to the corresponding side of the thumb.

For example, if your source image is 1280x800px and your thumb is 200x150px, you must resize your image to 240x150px and then crop it to 200x150px. This is so that the aspect ratio of the image won't change.

Here's a general formula for creating thumbnails:

$image = imagecreatefromjpeg($_GET['src']);
$filename = 'images/cropped_whatever.jpg'

$thumb_width = 200;
$thumb_height = 150;

$width = imagesx($image);
$height = imagesy($image);

$original_aspect = $width / $height;
$thumb_aspect = $thumb_width / $thumb_height;

if($original_aspect >= $thumb_aspect) {
   // If image is wider than thumbnail (in aspect ratio sense)
   $new_height = $thumb_height;
   $new_width = $width / ($height / $thumb_height);
} else {
   // If the thumbnail is wider than the image
   $new_width = $thumb_width;
   $new_height = $height / ($width / $thumb_width);
}

$thumb = imagecreatetruecolor($thumb_width, $thumb_height);

// Resize and crop
imagecopyresampled($thumb,
                   $image,
                   0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
                   0 - ($new_height - $thumb_height) / 2, // Center the image vertically
                   0, 0,
                   $new_width, $new_height,
                   $width, $height);
imagejpeg($thumb, $filename, 80);

Haven't tested this but it should work.

EDIT

Now tested and working.

Tatu Ulmanen
Thanks for the help, but its not working, i cant see anything wrong with the code?
Found a missing ;, but still didnt work, any advice?
Got it to work kind ofhttp://t-webdesign.co.uk/crop.php?src=http://extreme-showcase.com/wp-content/uploads/2009/08/whitetubes12.JPGBut its not working well vertically, any help?
Thanks, still not giving the right results tho see above link , thankssss
Okay, maybe I should test it myself first.. Gimme a sec and I'll post a fixed version.
Tatu Ulmanen
Brilliant thank you so much !