PHP の GD を使ってグラデーションを描画するサンプルです。
256階調を最大とし、開始色と終了色のミックス量を決めて混色するシンプルな仕組みです。
太さ 1px の線状にグラデーションを作り、 imagecopyresampled() を使って引き伸ばすことで高速化を図っています。
<?php
//キャンバスサイズ
$width = 300;
$height = 200;
//開始色
$start_r = 255;
$start_g = 255;
$start_b = 0;
//終了色
$end_r = 0;
$end_g = 255;
$end_b = 255;
//方向("vertical" 又は "horizontal")
$direction = "vertical";
$image = imagecreatetruecolor($width, $height);
if($direction === "horizontal"){
$grad_w = 256;
$grad_h = 1;
} else if($direction === "vertical"){
$grad_w = 1;
$grad_h = 256;
}
$gradient = imagecreatetruecolor( $grad_w, $grad_h);
for($i=0;$i<=255;$i++){
$mix = $i / 255;
$current_r = $start_r * (1 - $mix) + $end_r * $mix;
$current_g = $start_g * (1 - $mix) + $end_g * $mix;
$current_b = $start_b * (1 - $mix) + $end_b * $mix;
$color = imagecolorallocate($gradient, $current_r, $current_g, $current_b);
if($direction === "horizontal"){
imagesetpixel($gradient, $i, 0, $color);
} else if($direction === "vertical"){
imagesetpixel($gradient, 0, $i, $color);
}
}
imagecopyresampled($image, $gradient, 0, 0, 0, 0, $width, $height, $grad_w, $grad_h);
header("Content-type: image/jpeg");
imagejpeg($image);
imagedestroy($image);
imagedestroy($gradient);
グラデーションの開始と終了を RGB 値(それぞれ0~255)で指定します。
グラデーションの方向は垂直(vertical)と水平(horizontal)が選べます。




