我发现了一个非常有用的Ruby代码,用于删除图像白色背景颜色。
请参阅下面的参考代码: Remove white background from an image and make it transparent
我试图将代码翻译成php。但是我得到了一个不想要的结果。这是我第一次在这里发帖提问,有人可以给我一些指导并原谅我可怜的英语。
function setTransparency($new_image,$image_source)
{
$transparencyIndex = imagecolortransparent($image_source);
$transparencyColor = array('red' => 255, 'green' => 255, 'blue' => 255);
if ($transparencyIndex >= 0) {
$transparencyColor = imagecolorsforindex($image_source, $transparencyIndex);
}
$transparencyIndex = imagecolorallocate($new_image, $transparencyColor['red'], $transparencyColor['green'], $transparencyColor['blue']);
imagefill($new_image, 0, 0, $transparencyIndex);
imagecolortransparent($new_image, $transparencyIndex);
}
//create image from the source link
$image = imagecreatefrompng('http://i.stack.imgur.com/k7E1F.png');
//create image mask layer
$new_image = ImageCreateTruecolor(imagesx($image), imagesy($image));
//remove white background
setTransparency($new_image,$image);
//merge mask with original image source
ImageCopyMerge($new_image, $image, 0, 0, 0, 0, imagesx($image), imagesy($image), 100);
imagejpeg($new_image, null, 95);
答案 0 :(得分:5)
JPEG格式不支持透明度。您应该考虑使用png作为输出格式。将最后一行更改为:
imagepng($new_image, null, 9);