views:

85

answers:

2

I'm simply trying to crop a JPEG image (no scaling) using PHP. Here is my function, along with the inputs.

function cropPicture($imageLoc, $width, $height, $x1, $y1) {
    $newImage = imagecreatetruecolor($width, $height);

    $source = imagecreatefromjpeg($imageLoc);
    imagecopyresampled($newImage,$source,0,0,$x1,$y1,$width,$height,$width,$height);
    imagejpeg($newImage,$imageLoc,90);
}

When I call it as follows--cropPicture('image.jpg', 300, 300, 0, 0)--the function completes properly, but I'm left with a black image that is 300x300 px (in other words, a blank canvas). Am I passing in the wrong arguments?

The image exists and is writeable.

+2  A: 

A couple of things:

save the return values for imagecopyresampled and imagejpeg

One of those is not working properly, check which is false and that will narrow it down.

At first glance, I would look at reading and writing permissions first.

sobedai
+3  A: 

As an addition to sobedai's answer: Any of those functions you use in cropPicture() can fail. You have to test the return value of each and every one. In case of an error they return false and your function cannot continue (properly).

function cropPicture($imageLoc, $width, $height, $x1, $y1) {
  $newImage = imagecreatetruecolor($width, $height);
  if ( !$newImage ) {
    throw new Exception('imagecreatetruecolor failed');
  }

  $source = imagecreatefromjpeg($imageLoc);
  if ( !$source ) {
    throw new Exception('imagecreatefromjpeg');
  }

  $rc = imagecopyresampled($newImage,$source,0,0,$x1,$y1,$width,$height,$width,$height);
  if ( !$rc ) {
    throw new Exception('imagecopyresampled');
  }

  $rc = imagejpeg($newImage,$imageLoc,90);
  if ( !$rc ) {
    throw new Exception('imagejpeg');
  }
}

edit: You might also be interested in http://docs.php.net/error_get_last. The exception messages in the example script aren't that helpful...

VolkerK
Thanks a lot. I'll start coding like that from now on. The problem was in the function calling `cropPicture()`. So for future reference, my code above actually works!
thinkswan
But please don't throw exceptions _everywhere_ ;-) You can easily overuse them. see http://stackoverflow.com/questions/77127/when-to-throw-an-exception and http://stackoverflow.com/questions/1744070/why-should-exceptions-be-used-conservatively
VolkerK