首先,我在保存透明度的同时调整图像大小:
/*
all the classic routine etcetera:
$canvas = imagecreatefrom[png|gif|jpeg]();
$resize = imagecreatetruecolor();
*/
if($blending){
$transparentIndex = imagecolortransparent($canvas);
if($transparentIndex >= 0){
#GIF
imagepalettecopy($canvas, $resize);
imagefill($resize, 0, 0, $transparentIndex);
imagecolortransparent($resize, $transparentIndex);
imagetruecolortopalette($resize, true, 256);
}else{
#PNG
imagealphablending($resize, false);
imagesavealpha($resize, true);
$transparent = imagecolorallocatealpha($resize, 255, 255, 255, 127);
imagefill($resize, 0, 0, $transparent);
}
}
imagecopyresampled($resize, $canvas, 0, 0, 0, 0, $nx, $ny, $x, $y);
// image[png|gif|jpeg]... (image gets saved)
然后,我想对之前保存的图像(在新函数中)应用灰度滤镜:
/*
classic routine again:
$canvas = imagecreatefrom[png|gif|jpeg]()
*/
if($blending){
imagealphablending($canvas, false);
imagesavealpha($canvas, true);
}
imagefilter($canvas, IMG_FILTER_GRAYSCALE);
/*
This fully filters PNG's to Grayscale while saving transparency,
but for GIF, black background is added to my grayscaled picture,
plus, the picture isn't fully grayscale (more like gets high-contrasted with acidic colors).
*/
// image[png|gif|jpeg]
在将IMG_FILTER_GRAYSCALE应用到 gif
时保持透明度可以解决什么问题?
为了在保存透明度的同时将gif
转换为灰度,会有什么修复? (由于@Pierre提供的答案修改了问题)
提前致谢!
答案 0 :(得分:2)
与灰度滤镜一起使用的imagefilter会处理alpha通道。
但是,gif不支持alpha。因此,您将无法使用GIF格式存储它。
同样重要的是要注意背景颜色(单个颜色或颜色索引用作背景)与alpha(给定颜色或像素的透明度)无关。这意味着您有责任将背景颜色设置为所需的单色。
更新
不可能直接修改用作透明的颜色。这可以被视为一个错误,因为过滤器可能或应该忽略透明颜色。但这是另一个话题。
解决方法可能是:
$logo = imagecreatefromgif('php.gif');
$newimg = imagecreatetruecolor(imagesx($logo), imagesy($logo));
/* copy ignore the transparent color
* so that we can use black (0,0,0) as transparent, which is what
* the image is filled with when created.
*/
$transparent = imagecolorallocate($newimg, 0,0,0);
imagecolortransparent($newimg, $transparent);
imagecopy($newimg, $logo, 0,0, 0, 0,imagesx($logo), imagesx($logo));
imagefilter($newimg, IMG_FILTER_GRAYSCALE);
imagegif($newimg, 'a.gif');
此代码只需获取现有透明色的值,将其转换为灰色并将其设置回颜色索引。此代码仅适用于像gif这样的调色板图像,但这就是主意。