我想刪除在PHP平臺上工作的網站上上傳的任何圖像的白色背景。上傳功能已完成,但與此功能混淆。使用php刪除圖像背景並保存透明PNG
這裏是我發現這裏的鏈接: Remove white background from an image and make it transparent
但這反向做。我想刪除彩色背景並使其具有透明背景的圖像。
我想刪除在PHP平臺上工作的網站上上傳的任何圖像的白色背景。上傳功能已完成,但與此功能混淆。使用php刪除圖像背景並保存透明PNG
這裏是我發現這裏的鏈接: Remove white background from an image and make it transparent
但這反向做。我想刪除彩色背景並使其具有透明背景的圖像。
使用php圖像處理和GD,如果RGB分量全部爲255(像素爲白色),則將像素逐像素地讀取 ,將alpha通道設置爲255(透明)。取決於上傳的文件類型是否支持Alpha通道,您可能必須更改圖像 的文件類型。
由於您只需要單色透明度,最簡單的方法是用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);
我試過了但在屏幕上顯示不需要的字符: $ 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); –
請詳細說明'不需要的字符'。 – Maerlyn
這是一個警告(imagefill()獲取無效資源),然後是一個PNG圖像。 – Maerlyn
獲取圖像中白色的索引並將其設置爲透明。
$whiteColorIndex = imagecolorexact($img,255,255,255);
$whiteColor = imagecolorsforindex($img,$whiteColorIndex);
imagecolortransparent($img,$whiteColor);
如果您不知道確切的顏色,則可以使用imagecolorclosest()。
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');
嘗試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;
}
從@ 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);
請註明爲零下投票的原因 –
解釋更向我們展示你做了什麼,我不是那個低調的人。 –
我剛編輯我的問題。 –