PHP 在 Imagick 中删除 alpha 会导致图片损坏

PHP removing alpha in Imagick results in corrupted picture

我有一张带图片的 URL。我将图像保存在一个变量中。如果我用 Imagick 加载变量,图像是在删除 alpha 损坏之后。

代码:

$image = new Imagick();
$image->readImageBlob($picture);
$image->writeImage ("test.png");

代码:

$image = new Imagick();
$image->readImageBlob($picture);
$image->setImageBackgroundColor('white');
$image->setImageAlphaChannel(11);
$image->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
$image->writeImage ("test.png");

PHP 版本 7.3.11

imagick 模块版本:3.4.4RC2

用ImageMagick编译的Imagick版本:ImageMagick 7.0.7-11 Q16 x64 2017-11-23

ImageMagick 发布日期:2017-11-23

图像在 "setImageAlphaChannel" 后立即损坏。源文件是否导致问题?如果是,有没有办法修复损坏的图像?

提前致谢!

编辑:

这是我的完整代码:

<?php


$url="https://i.imgur.com/jD5hRgO.png";

$ch = curl_init(); 
curl_setopt ($ch, CURLOPT_URL, $url); 
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6"); 
curl_setopt ($ch, CURLOPT_TIMEOUT, 60); 
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1); 
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt ($ch, CURLOPT_REFERER, $url); 
$picture = curl_exec ($ch); 
curl_close($ch);

$image = new Imagick();
$image->readImageBlob($picture);
$image->writeImage ("before.png");


$image = new Imagick();
$image->readImageBlob($picture);
$image->setImageBackgroundColor('white');
$image->setImageAlphaChannel(11);
$image->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
$image->writeImage ("after.png");


?>

您想使用 Imagick::ALPHACHANNEL_REMOVE.

$image = new Imagick();
$image->readImageBlob($picture);
$image->setImageBackgroundColor('white');
$image->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE);
$image->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
$image->writeImage ("after.png");

这将用背景颜色替换 透明像素。

The image is broken right after "setImageAlphaChannel". Is the source file causing the issue?

并没有真正损坏,但问题是由源文件引起的。将 alpha 通道设置为 11(即 C-API 中的 OpaqueAlphaChannel)将强制 "hidden" 颜色值不透明。在您的示例中,看不见的 RGB 数据是生成图像的作者留下的人工产物。

If yes, is there a way to repair the broken image?

不!您需要从源代码重做损坏的文件。应用 -alpha opaque 会破坏 alpha 蒙版。

引自 "Masks" 用法文章...

The original 'shape' of the image can no longer be recovered after this operation as the original alpha channel data has been overwritten.