1
votes

I need help. I try to use imagecropauto(), but PNG still getting black background. Here is the code:

$im = imagecreatefrompng($imgPath);

imagealphablending($im, false);
imagesavealpha($im, true);

// if imagepng($im...) called here, original PNG is saved with transparency

// if I use IMG_CROP_TRANSPARENT - crop doesn't works
// IMG_CROP_SIDES working how I expect
$cropped = imagecropauto($im, IMG_CROP_SIDES);

if ($cropped !== false) {
    // destroy old image
    imagedestroy($im);

    imagealphablending($cropped, false);
    imagesavealpha($cropped, true);

    // save cropped image with black background
    imagepng($cropped, $imgPath);
    imagedestroy($cropped);
}

Any suggestion what's wrong?

EDIT: PNG image is transparent by alpha channel on points, so some points have lower opacity then other. If I use imagealphablending - true (default) I can only set one color to be transparent and result has black line around picture.

Default: enter image description here

With imageblending - true and black color is transparent: enter image description here

1

1 Answers

3
votes

I have the issue on Ubuntu too, on windows it works perfectly fine. My code is exactly like yours. The issue is confirmed and not fixed yet.

Here is a link related to this issue

And in my case, I'm ok with the white background, here is how:

  $width = imagesx($im);
  $height = imagesy($im);
  $new = imagecreatetruecolor($width, $height);
  $white = imagecolorallocate($new, 255, 255, 255);
  //now the image is purely white
  imagefill($new, 0, 0, $white);
  //place the transparent image onto this white background image
  imagecopyresampled($new, $im, 0, 0, 0, 0, $width, $height, $width, $height);

  //crop the new image
  $white = imagecolorat($new, 1, $height - 1);
  $cropped = imagecropauto($new, IMG_CROP_THRESHOLD, 0.5, $white);

  if ($cropped) {
    imagepng($cropped, $output_file);
    imagedestroy($cropped);
  }