2012-04-05 3 views
1

イメージがあるとします(パスポートタイプのイメージで、イメージ内の特定の背景色の透過率をイメージに設定するにはどうすればいいですか?PHP-GDを使用して

私がしたいことは、その背景イメージをPHP GDを使用して透明にすることです。だから私はこれをどのように達成できるのか教えてください。サンプル画像はここに表示されています。私は黄色を透明にしたい。 enter image description here

答えて

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の中でそれを入力したので、私はいくつかの遅れスペルミスを持っているかもしれないが、それはあなたの裸の極小点ですべき正しい方向に。

+1

+1作品80%....素敵なもの – Baba

+0

構文エラーが見つかった場合は、私が教えてくれたように、ソースを悪く編集して、他の人にも役立ちます。必ずMAX_DIFFERENCEで混乱させてください。使用できるその他の機能強化は、現在のピクセルの左/右/上/下にピクセルを比較して、MAX_DIFFERENCEに近いかどうかを確認して、M_D変数を高くしすぎないように精度を向上させることです。また、上でプログラムしたように、バイナリのON/OFFではなく、勾配関数のラインsin/cosを利用することもできます。画像編集の世界へようこそ!] –

+0

これを見て今どのように改善できるか見ています..これまではうまく仕事ができています...... – Baba