用php删除图像背景并保存透明png

时间:2012-05-25 08:43:44

标签: php

我想删除在PHP平台上工作的网站上传的任何图片的白色背景。上传功能已完成但与此功能混淆。

以下是我在此处找到的链接: Remove white background from an image and make it transparent

但这反过来了。我想删除彩色背景并使其具有透明背景图像。

7 个答案:

答案 0 :(得分:4)

由于您只需要单色透明,最简单的方法是使用imagecolortransparent()定义白色。这样的事情(未经测试的代码):

$img = imagecreatefromstring($your_image); //or whatever loading function you need
$white = imagecolorallocate($img, 255, 255, 255);
imagecolortransparent($img, $white);
imagepng($img, $output_file_name);

答案 1 :(得分:4)

function transparent_background($filename, $color) 
{
    $img = imagecreatefrompng('image.png'); //or whatever loading function you need
    $colors = explode(',', $color);
    $remove = imagecolorallocate($img, $colors[0], $colors[1], $colors[2]);
    imagecolortransparent($img, $remove);
    imagepng($img, $_SERVER['DOCUMENT_ROOT'].'/'.$filename);
}

transparent_background('logo_100x100.png', '255,255,255');

答案 2 :(得分:3)

尝试ImageMagick它为我做了诀窍。您还可以控制需要删除的颜色数量。只需传递图像路径,bgcolor作为RGB数组,并以百分比形式显示模糊。只要您在系统/主机上安装了ImageMagick。我有我的托管服务提供商为我安装模块。

我正在使用ImageMagick版本6.2.8

示例:

    $image = "/path/to/your/image.jpg";
    $bgcolor = array("red" => "255", "green" => "255", "blue" => "255");
    $fuzz = 9;
    remove_image_background($image, $bgcolor, $fuzz); 

        protected function remove_image_background($image, $bgcolor, $fuzz)
        {
            $image = shell_exec('convert '.$image.' -fuzz '.$fuzz.'% -transparent "rgb('.$bgcolor['red'].','.$bgcolor['green'].','.$bgcolor['blue'].')" '.$image.'');
            return $image;
        }

答案 3 :(得分:1)

获取图像中的白色索引并将其设置为透明。

$whiteColorIndex = imagecolorexact($img,255,255,255);
$whiteColor = imagecolorsforindex($img,$whiteColorIndex);
imagecolortransparent($img,$whiteColor);

如果您不知道确切的颜色,也可以使用imagecolorclosest()。

答案 4 :(得分:1)

来自@ geoffs3310的函数应该是这里接受的答案,但请注意,保存的png不包含alpha通道。

要删除背景并将新png保存为带alpha的透明png,以下代码可以正常工作

$_filename='/home/files/IMAGE.png';
$_backgroundColour='0,0,0';
$_img = imagecreatefrompng($_filename);
$_backgroundColours = explode(',', $_backgroundColour);
$_removeColour = imagecolorallocate($_img, (int)$_backgroundColours[0], (int)$_backgroundColours[1], (int)$_backgroundColours[2]);
imagecolortransparent($_img, $_removeColour);
imagesavealpha($_img, true);
$_transColor = imagecolorallocatealpha($_img, 0, 0, 0, 127);
imagefill($_img, 0, 0, $_transColor);
imagepng($_img, $_filename);

答案 5 :(得分:0)

使用php图像处理和GD,逐像素读取图像 如果RGB分量全部为255(像素为白色),则设置alpha 通道为255(透明)。您可能必须更改图像的文件类型 取决于上传的文件类型是否支持Alpha通道。

答案 6 :(得分:0)

从网址版本转换到网页并返回页面:

$img = imagecreatefromjpeg('http://mypage.com/image.jpg');

$remove = imagecolorallocate($img, 255, 255, 255); // Define color rgb to remove
imagecolortransparent($img, $remove);

ob_start();
imagepng($img);
$imgData = ob_get_clean();
imagedestroy($img);

$data_img = 'data:image/png;base64,'.base64_encode($imgData);
echo '<body style="background: #f00;"><img src="'.$data_img.'"></body>';