有時候我們需要給圖片的熱區畫線,這時候我們就要使用PHP的GD庫了。熱區的點數是不定的,圖片的大小也是不定的,我們可以使用下面的方法生成圖片的熱區。
<?php
header("Content-type: image/jpeg");
$width = 400;
$height = 300;
$image = imagecreate(400, 300);
$white = imagecolorallocate($image, 0xf5, 0xf5, 0xf5);
$red = imagecolorallocate($image, 0xff, 0x00, 0x00);
$blue = imagecolorallocate($image, 204, 255, 0);
$blue2 = imagecolorallocate($image, 0, 0, 0);
$line_string ="65.616350%,6.142129%,50.894733%,6.142129%,49.632880%,12.764112%,17.665940%,12.764112%,16.544293%,6.142129%,2.663912%,6.142129%,2.663912%,29.558995%,65.616350%,29.558995%";
$line_array = explode(",",$line_string);
for($i = 0; $i < count($line_array); $i=$i+2)
{
if($i <= count($line_array) - 4)
{
imageline($image, $line_array[$i] / 100 * $width, $line_array[$i+1] / 100 * $height, $line_array[$i+2] / 100 * $width, $line_array[$i+3] / 100 * $height, $blue);
}
else
{
imageline($image, $line_array[$i] / 100 * $width, $line_array[$i+1] / 100 * $height, $line_array[0] / 100 * $width, $line_array[1] / 100 * $height, $blue);
}
}
imagejpeg($image);
//imagejpeg($image,"test.jpg",80); //保存圖片.80為圖片質量
//推薦用ImagePNG()輸出,這樣圖片質量要好些,文件大小也小些
?>
語法: int imageline(int im, int x1, int y1, int x2, int y2, int col);
本函數將在圖形上畫出一條實線。從 x1、y1 連接到 x2、y2,原點 (0,0) 為圖形的左上角。參數 col 為實線的顏色。
參考例子:
<?php
function imagelinethick ( $image , $x1 , $y1 , $x2 , $y2 , $color , $thick = 1 )
{
/* 下面兩行只在線段直角相交時好使
imagesetthickness($image, $thick);
return imageline($image, $x1, $y1, $x2, $y2, $color);
*/
if ( $thick == 1 ) {
return imageline ( $image , $x1 , $y1 , $x2 , $y2 , $color );
}
$t = $thick / 2 - 0.5 ;
if ( $x1 == $x2 || $y1 == $y2 ) {
return imagefilledrectangle ( $image , round ( min ( $x1 , $x2 ) - $t ), round ( min ( $y1 , $y2 ) - $t ), round ( max ( $x1 , $x2 ) + $t ), round ( max ( $y1 , $y2 ) + $t ), $color );
}
$k = ( $y2 - $y1 ) / ( $x2 - $x1 ); //y = kx + q
$a = $t / sqrt ( 1 + pow ( $k , 2 ));
$points = array(
round ( $x1 - ( 1 + $k )* $a ), round ( $y1 + ( 1 - $k )* $a ),
round ( $x1 - ( 1 - $k )* $a ), round ( $y1 - ( 1 + $k )* $a ),
round ( $x2 + ( 1 + $k )* $a ), round ( $y2 - ( 1 - $k )* $a ),
round ( $x2 + ( 1 - $k )* $a ), round ( $y2 + ( 1 + $k )* $a ),
);
imagefilledpolygon ( $image , $points , 4 , $color );
return imagepolygon ( $image , $points , 4 , $color );
}
?>
為一幅圖像分配顏色。
imagecolorallocate() 返回一個標識符,代表了由給定的 RGB 成分組成的顏色。 image 參數是 imagecreatetruecolor() 函數的返回值。 red , green 和 blue 分別是所需要的顏色的紅,綠,藍成分。這些參數是 0 到 255 的整數或者十六進制的 0x00 到 0xFF。 imagecolorallocate() 必須被調用以創建每一種用在 image 所代表的圖像中的顏色。
第一次對 imagecolorallocate() 的調用會填充背景色。
<?php $im = imagecreatetruecolor ( 'example.jpg' ); // 背景設為紅色 $background = imagecolorallocate ( $im , 255 , 0 , 0 ); // 設定一些顏色 $white = imagecolorallocate ( $im , 255 , 255 , 255 ); $black = imagecolorallocate ( $im , 0 , 0 , 0 ); // 十六進制方式 $white = imagecolorallocate ( $im , 0xFF , 0xFF , 0xFF ); $black = imagecolorallocate ( $im , 0x00 , 0x00 , 0x00 ); ?>
本函數用來匹配圖形的顏色,供其它繪圖函數使用。參數 im 表示圖形的 handle。參數 red、green、blue 是色彩三原色,其值從 0 至 255。