开发者

Image cropping in PHP is producing blank result

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 t开发者_开发问答hat is 300x300 px (in other words, a blank canvas). Am I passing in the wrong arguments?

The image exists and is writeable.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜