2012-04-05 34 views

回答

2

你基本上想要做的是将颜色'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

+1作品80%.... nice one – Baba 2012-04-05 15:41:51

+0

如果您发现任何语法错误,请让我知道并编辑错误的源代码,以便对其他人也是有用的。一定要弄乱MAX_DIFFERENCE。您可以使用的其他增强功能是,您可以将像素与当前像素的左/右/上/下进行比较,以查看它们与MAX_DIFFERENCE的接近程度,以便在不将M_D变量调高的情况下获得更高的精度。您也可以使用梯度函数行sin/cos,而不是像我上面编程的那样使用二进制ON/OFF。欢迎来到图像编辑的世界=]! – 2012-04-05 15:44:20

+0

我现在看看它是如何改善..迄今..是一个工作做得好...... – Baba 2012-04-05 15:52:21

相关问题