如何使用PHP-GD为图像中的特定背景颜色设置透明度

时间:2012-04-05 15:13:30

标签: php gd php-5.3

假设我有任何图像(比如护照类型图像,其背景在用户周围是相同的)。

我想要做的是使用PHP GD将背景图像变为透明。所以,请让我知道如何实现这一目标?此处显示示例图像。我希望黄色是透明的。 enter image description here

1 个答案:

答案 0 :(得分:2)

您基本上想要做的是将颜色“贴近”替换为背景颜色。 “靠近”我的意思是与它相似的颜色:

// $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);

请注意上面的代码是未经测试的,我只是在stackoverflow中键入它,所以我可能会有一些延迟的拼写错误,但它应该在最小的点上你正确的方向。