7

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

这是我在这里找到的链接: 从图像中删除白色背景并使其透明

但这正在做相反的事情。我想删除彩色背景并使其具有透明背景的图像。

4

7 回答 7

6

由于您只需要单色透明度,因此最简单的方法是使用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);
于 2012-05-25T08:55:56.077 回答
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');
于 2012-11-13T14:48:38.773 回答
3

试试 ImageMagick,它对我有用。您还可以控制需要去除的颜色量。只需将图像路径、bgcolor 作为 RGB 数组传递,并以百分比形式传递 fuzz。只要您在系统/主机上安装了 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;
        }
于 2015-04-08T14:20:51.567 回答
1

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

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

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

于 2012-05-25T08:59:28.667 回答
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);
于 2017-04-07T08:45:48.907 回答
0

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

于 2012-05-25T08:49:13.057 回答
0

从 URL 转换并返回页面的版本:

$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>';
于 2020-11-12T14:42:36.590 回答