1
假設我有任何圖像(比如護照類型的圖像,其背景在用戶周圍是相同的)。如何設置透明度爲圖像中的特定背景顏色的圖像 - 使用PHP - GD
我想要做的就是使用PHP GD將背景圖像設置爲透明。所以,請讓我知道我該如何做到這一點?示例圖像顯示在這裏。我想讓黃色變得透明。
假設我有任何圖像(比如護照類型的圖像,其背景在用戶周圍是相同的)。如何設置透明度爲圖像中的特定背景顏色的圖像 - 使用PHP - GD
我想要做的就是使用PHP GD將背景圖像設置爲透明。所以,請讓我知道我該如何做到這一點?示例圖像顯示在這裏。我想讓黃色變得透明。
你基本上想要做的是將顏色'close'替換爲背景顏色。通過「關閉」我的意思是類似於它的顏色:
// $src, $dst......
$src = imagecreatefromjpeg("dmvpic.jpg");
// Alter this by experimentation
define("MAX_DIFFERENCE", 20);
// How 'far' two colors are from one another/color similarity.
// Since we aren't doing any real calculations with this except comparison,
// you can get better speeds by removing the sqrt and just using the squared portion.
// There may even be a php gd function that compares colors already. Anyone?
function dist($r,$g,$b) {
global $rt, $gt, $bt;
return sqrt(($r-$rt)*($r-$rt) + ($g-$gt)*($g-$gt) + ($b-$bt)*($b-$bt));
}
// Alpha color (to be replaced) is defined dynamically as
// the color at the top left corner...
$src_color = imagecolorat($src ,0,0);
$rt = ($src_color >> 16) & 0xFF;
$gt = ($src_color >> 8) & 0xFF;
$bt = $src_color & 0xFF;
// Get source image dimensions and create an alpha enabled destination image
$width = imagesx($src);
$height = imagesy($src);
$dst = =imagecreatetruecolor($width, $height);
imagealphablending($dst, true);
imagesavealpha($dst, true);
// Fill the destination with transparent pixels
$trans = imagecolorallocatealpha($dst, 0,0,0, 127); // our transparent color
imagefill($dst, 0, 0, $transparent);
// Here we examine every pixel in the source image; Only pixels that are
// too dissimilar from our 'alhpa' or transparent background color are copied
// over to the destination image.
for($x=0; $x<$width; ++$x) {
for($y=0; $y<$height; ++$y) {
$rgb = imagecolorat($src, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
if(dist($r,$g,$b) > MAX_DIFFERENCE) {
// Plot the (existing) color, in the new image
$newcolor = imagecolorallocatealpha($dst, $r,$g,$b, 0);
imagesetpixel($dst, $x, $y, $newcolor);
}
}
}
header('Content-Type: image/png');
imagepng($dst);
imagedestroy($dst);
imagedestroy($src);
請注意上面的代碼是未經測試,我剛纔輸入它的計算器,所以我可能有一些滯後拼寫錯誤,但它應該在裸露的最低點你在正確的方向。
+1作品80%.... nice one – Baba 2012-04-05 15:41:51
如果您發現任何語法錯誤,請讓我知道並編輯錯誤的源代碼,以便對其他人也是有用的。一定要弄亂MAX_DIFFERENCE。您可以使用的其他增強功能是,您可以將像素與當前像素的左/右/上/下進行比較,以查看它們與MAX_DIFFERENCE的接近程度,以便在不將M_D變量調高的情況下獲得更高的精度。您也可以使用梯度函數行sin/cos,而不是像我上面編程的那樣使用二進制ON/OFF。歡迎來到圖像編輯的世界=]! – 2012-04-05 15:44:20
我現在看看它是如何改善..迄今..是一個工作做得好...... – Baba 2012-04-05 15:52:21