2012-05-25 83 views
5

我想删除在PHP平台上工作的网站上上传的任何图像的白色背景。上传功能已完成,但与此功能混淆。使用php删除图像背景并保存透明PNG

这里是我发现这里的链接: Remove white background from an image and make it transparent

但这反向做。我想删除彩色背景并使其具有透明背景的图像。

+3

请注明为零下投票的原因 –

+0

解释更向我们展示你做了什么,我不是那个低调的人。 –

+0

我刚编辑我的问题。 –

回答

0

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

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); 
+0

我试过了但在屏幕上显示不需要的字符: $ file ='itsmehere.png'; // path to png图片 $ img = imagecreatefrompng($ file); // open image $ white = imagecolorallocate($ img,255,255,255); imagecolortransparent($ img,$ color); 012gimagepng($ img,$ output_file_name); –

+0

请详细说明'不需要的字符'。 – Maerlyn

+0

这是一个警告(imagefill()获取无效资源),然后是一个PNG图像。 – Maerlyn

1

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

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

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

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

尝试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; 
     } 
0

从@ geoffs3310的功能应该是在这里接受的答案,但要注意,即保存PNG不包含alpha渠道。

去除背景和新的PNG保存为阿尔法透明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);