0x01 将输出类型改为图像流
通过设置文件的MIME类型将text/html改为图像流
header('Content-Type:image/png;');
png的压缩方式是无损压缩,而jpg的破坏性压缩会导致图片在多次保存后质量下降。
0x02 创建一个图形区域
通常采用imagecreatetruecolor()返回类型是resource(资源)类型
resource imagecreatetruecolor ( int $width , int $height )
两个参数分别是宽和高。
0x03 输出图像
imagepng() 以 PNG 格式将图像输出到浏览器或文件
imagejpeg() 以 JPG格式将图像输出到浏览器或文件
imagegif() 以 GIF格式将图像输出到浏览器或文件
我们选择的是png格式,因此用imagepng输出,三个函数的返回值都是bool型。
bool imagepng ( resource $image [, string $filename ] )
如果此时输出,由于没有填充,输出是默认的黑色。但是已经能看见那个黑框了。
0x04 设置背景色
imagecolorallocate()
int imagecolorallocate ( resource $image , int $red , int $green , int $blue )
四个参数分别是资源地址,RGB值。
设置好之后,将颜色填充到刚刚的黑色区域。用imagefill()
int imagecolorallocate ( resource $image , int $red , int $green , int $blue )
0x05 加入其他元素
线条:imageline()
bool imageline ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color )
看参数就基本知道了。
文字:imagestring() 水平写一行字符
bool imagestring ( resource $image , int $font , int $x , int $y , string $s , int $col )
这里的font是大小,从1-5递增。
下面是我的参考样例,看看就行
<?php
header('Content-Type:image/png;');
$img = imagecreatetruecolor(1920,1200);
$bgcolor = imagecolorallocate($img, 255, 0, 0);//红
imagefill($img,0,0,$bgcolor);
$linecolor = imagecolorallocate($img,255,255,255);
imageline($img,0,0,1920,1200,$linecolor);//斜着劈下来的白线
$strcolor = imagecolorallocate($img,0,0,255);
imagestring($img,5,400,200,'Crazy9',$strcolor);//5号字太小了
imagepng($img);
imagedestroy($img);//记得销毁图像
对于颜色比较单一,色彩要求不高的,建议用GIF格式保存。节省空间。