PHP 5.5 imagecropauto()失去了透明度

时间:2018-04-13 07:46:39

标签: php png transparency

我需要帮助。 我尝试使用imagecropauto(),但PNG仍然获得黑色背景。这是代码:

$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);
}

有什么建议吗?

编辑: PNG图像在点上的alpha通道是透明的,因此某些点的不透明度低于其他点。如果我使用imagealphablending - true(默认)我只能将一种颜色设置为透明,结果在图片周围有黑线。

默认: enter image description here

使用imageblending - 真实和黑色是透明的: enter image description here

1 个答案:

答案 0 :(得分:2)

我也在Ubuntu上也遇到了问题,在Windows上它工作得很好。 我的代码与您的代码完全一样。 The issue已确认,尚未确定。

Here is a link related to this issue

就我而言,我对白色背景没问题,这是如何做的:

  $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);
  }
相关问题