Question

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.

Was it helpful?

Solution

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...

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top