Sunday, December 19, 2010

PHPとGDでグラデーションのかかった画像に変換する

PHPとGDでグラデーションのかかった画像に変換するには、以下のコードを実行します。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="ja"
xml:lang="ja" dir="ltr">
<head>
<title>gd_test4</title>
</head>
<body>
<?php
// 入力ファイル名
$fn = "sf.jpg";
// 入力ファイルサイズ取得
$bimg = imagecreatefromjpeg($fn);
imagefilter($bimg, IMG_FILTER_GRAYSCALE);
$sx = imagesx($bimg);
$sy = imagesy($bimg);
// グラデーション用画像を作成
$img = imagecreate($sx, $sy);
imagesavealpha($img, true);
imagealphablending($img, false);
// 半透明グラデーションを作成
$c1 = 0xffff10;
$c2 = 0x3070a0;
for($ly=0;$ly<$sy;$ly++){
$r1 = ($c1 >> 16) & 0xff;
$g1 = ($c1 >> 8 ) & 0xff;
$b1 = $c1 & 0xff;
$r2 = ($c2 >> 16) & 0xff;
$g2 = ($c2 >> 8 ) & 0xff;
$b2 = $c2 & 0xff;
$ro = $r1 + round(($r2 - $r1)/$sy*$ly);
$go = $g1 + round(($g2 - $g1)/$sy*$ly);
$bo = $b1 + round(($b2 - $b1)/$sy*$ly);
for($lx=0;$lx<$sx;$lx++){
imagesetpixel($img, $lx, $ly,
imagecolorresolve($img, $ro, $go, $bo));
}
}

// 重ね合わせ
imagecopymerge($bimg, $img, 0, 0, 0, 0, $sx, $sy, 50);

// ファイル出力
imagepng($bimg, "gd_test4.png");
// 開放
imagedestroy($bimg);
imagedestroy($img);
?>
<img src="gd_test4.png" /><br />
</body>
</html>



元画像


出力画像


動作環境
Apache httpd 2.2.17, PHP5.3.3

No comments: