PHP GD库图像创建与基础绘图函数
检查GD模块支持情况是进行图像操作的前提。
if(!function_exists('imagecreate')) {
die('本服务器不支持GD模块');
}
若环境缺失该支持,需下载对应的gd模块dll文件,修改php.ini配置并重启服务器以启用功能。
下文将PHP图像编程简称为PS。
执行图像创作需遵循标准步骤,这是不可省略的流程。
第一步:构建基础PS对象(假设变量名为$image),并填充背景色(默认为黑色),后续所有绘图操作均基于此背景图像展开。
第二步:在已创建的$image对象上进行具体的图形绘制。
第三步:将绘制完成的图像数据输出至浏览器或保存为文件。
第四步:销毁图像对象,释放所占用的系统内存。
首先介绍几个核心函数,这些在PHP手册中有详尽说明,此处仅作概要引用。
resource imagecreate ( int x_size, int y_size )
imagecreate() 函数返回一个图像标识符,代表一幅尺寸为 x_size 和 y_size 的空白图像。
此函数的基本用途与 imagetruecolor($width,$height) 类似。
---------------------------------------------------------
int imagecolorallocate ( resource image, int red, int green, int blue )
imagecolorallocate() 返回一个颜色标识符,由指定的 RGB 成分组成。image 参数通常来自 imagecreatetruecolor() 的返回值。red、green 和 blue 分别代表红、绿、蓝分量,取值范围为 0 到 255 或十六进制 0x00 到 0xFF。必须在图像中使用每种颜色前调用此函数进行分配。
---------------------------------------------------------
bool imagefill ( resource image, int x, int y, int color )
imagefill() 在图像坐标 x,y 处(左上角为 0, 0)使用 color 颜色执行区域填充,即填充与指定点颜色相同且相邻的所有像素。
---------------------------------------------------------
bool imageline ( resource image, int x1, int y1, int x2, int y2, int color )
imageline() 使用 color 颜色在图像 image 中从坐标 x1,y1 到 x2,y2(左上角为 0, 0)绘制一条线段。
---------------------------------------------------------
bool imagestring ( resource image, int font, int x, int y, string s, int col )
imagestring() 使用 col 颜色将字符串 s 绘制到图像 image 的 x,y 坐标处(此为字符串左上角坐标,整图左上角为 0,0)。若 font 取值为 1、2、3、4 或 5,则使用内置字体。
---------------------------------------------------------
array imagettftext ( resource image, float size, float angle, int x, int y, int color, string fontfile, string text )
该函数较为重要且参数较多,此处不再逐一列出。它主要用于向图像写入文字,功能比前述函数更强大。
---------------------------------------------------------
bool imagefilltoborder ( resource image, int x, int y, int border, int color )
imagefilltoborder() 从 x,y(左上角为 0, 0)点开始用 color 颜色执行区域填充,直到碰到颜色为 border 的边界为止。【注:边界内的所有颜色都会被填充。如果指定的边界色和该点颜色相同,则没有填充。如果图像中没有该边界色,则整幅图像都会被填充。】
------------------------------------------------
bool imagefilledellipse ( resource image, int cx, int cy, int w, int h, int color )
imagefilledellipse() 在图像 image 中以 cx,cy(左上角为 0, 0)为中心绘制并填充一个椭圆。w 和 h 分别指定椭圆的宽和高。椭圆使用 color 颜色填充。成功返回 TRUE,失败返回 FALSE。
=================================================
输出图像数据的方法为: imagepng($image[,$filename])
======================================================
基础图形绘制与阴阳图生成示例
例一: 输出蓝色背景和交叉白线的图形
<?php
$width=35;
$height=35;
//创建对象
$image=imagecreate($width,$height);
//提取颜色
$color_white=imagecolorallocate($image,255,255,255);//白色
$color_blue=imagecolorallocate($image,0,0,108);//蓝色
imagefill($image,0,0,$color_blue);
//作图
//线宽
imagesetthickness($image,3);
imageline($image,0,0,$width,$height ,$color_white);
imageline($image,$width,0,0,$height ,$color_white);
//发送对象至头
header('content-type:image/png');
imagepng($image);
/*
//发送对象至文件
$filename="ex1.png";
imagepng($image,$filename);
*/
//销毁对象
imagedestroy($image);
?>
输出图像:
在线演示:http://www.phzzy.org/temp/5do8/ex1.php
例二: 阴阳图
<?php
$width=400;
$height=400;
$image=imagecreatetruecolor($width,$height);
//提取颜色
$color_black=imagecolorallocate($image,0,2,0);//
$color_white=imagecolorallocate($image,255,255,255);//白色
$color_blue=imagecolorallocate($image,0,0,108);//蓝色
$color_red=imagecolorallocate($image,151,0,4);//红色
$color_my=imagecolorallocate($image,192,192,255);//背景
$color_temp=imagecolorallocate($image,199,199,199);//背景
//作图
imagefill($image,0,0,$color_white);
//第一个是大圆
imagefilledarc ($image,$width/2,$height/2,$height,$height,0,360,$color_blue,IMG_ARC_PIE);
//两个小圆
imagefilledellipse ($image,$width/2,$height/4 ,$height/2,$height/2,$color_red);
imagefilledellipse ($image,$width/2,$height/4 * 3,$height/2,$height/2,$color_blue);
/*imagefilledellipse -- 画一椭圆并填充*/
imagefilledarc ($image,$width/2,$height/2,$height,$height,-90,90,$color_red,IMG_ARC_PIE);
imagefilledellipse ($image,$width/2,$height/4 * 3,$height/2,$height/2,$color_blue);
//发送对象至头
header('content-type:image/png');
imagepng($image);
/*
//发送对象至文件
$filename="ex1.png";
imagepng($image,$filename);
*/
//销毁对象
imagedestroy($image);
?>
演示:
http://www.phzzy.org/temp/5do8/ex2.php
例三:3D图像--cool
<?php
$width=400;
$height=400;
$image = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
$gray = imagecolorallocate($image, 0xC0, 0xC0, 0xC0);
$darkgray = imagecolorallocate($image, 0x90, 0x90, 0x90);
$navy = imagecolorallocate($image, 0x00, 0x00, 0x80);
$darknavy = imagecolorallocate($image, 0x00, 0x00, 0x50);
$red = imagecolorallocate($image, 0xFF, 0x00, 0x00);
$darkred = imagecolorallocate($image, 0x90, 0x00, 0x00);
imagefill($image,0,0,$white);
// make the 3D effect
for ($i = $height /2 +20; $i > $height /2; $i--) {
imagefilledarc($image, $width/2, $i, $width/2, $height /2, 0, 45, $darknavy, IMG_ARC_PIE);
imagefilledarc($image, $width/2, $i, $width/2, $height /2, 45, 75 , $darkgray, IMG_ARC_PIE);
imagefilledarc($image, $width/2, $i, $width/2, $height /2, 75, 360 , $darkred, IMG_ARC_PIE);
}
imagefilledarc($image, $width/2, $height /2, $width/2, $height /2, 0, 45, $navy, IMG_ARC_PIE);
imagefilledarc($image, $width/2, $height /2, $width/2, $height /2, 45, 75 , $gray, IMG_ARC_PIE);
imagefilledarc($image, $width/2, $height /2, $width/2, $height /2, 75, 360 , $red, IMG_ARC_PIE);
// flush image
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
/*
//发送对象至文件
$filename="ex1.png";
imagepng($image,$filename);
*/
?>
输出:
演示:http://www.phzzy.org/temp/5do8/ex3.php
简单验证码与增强型验证码实现
例四:简单的验证码
PHP创建验证码非常简单,基本思路如下:
随机种子生成,提取随机字符,将其打印到图形上并输出。为防止色盲用户识别困难,可随机提取颜色或自定义颜色集,具体实现见下文。
<?php
session_start();
$width=65;
$height=20;
$sourcestrings="0123456789aqwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
$image=imagecreate($width,$height);
$colorarrs=array(
imagecolorallocate($image,255,255,255),//white
imagecolorallocate($image,0 ,0 , 0)//black
);
unset($sessionval);
imagesetthickness($image,3);
//随机得到字符串个数
$strsize=rand(3,5);
imagefill($image,0,0,$colorarrs[0]);
//一个个的写字符串到图片
for($i=0;$i<$strsize;$i++){
$i_temp=rand(1,62);
$sessionval .=$sourcestrings[$i_temp];
$fontcolor=imagecolorallocate($image,rand(0,255),rand(0,255),rand(0,255));
$y_i = $height/2 + $font_size /3 ;
imagechar($image,5, 1+ $i * $width /$strsize,5,$sourcestrings[$i_temp],$fontcolor);
}
//写入session,以后验证用
unset($_SESSION['cjjer']);
$_SESSION['cjjer'] = $sessionval;
//添加杂点
for($i=0;$i<$width /$height *2;$i++)
{ $i_x=rand(0,$width);
$i_y=rand(0,$height);
$pixelcolor=imagecolorallocate($image,rand(0,255),rand(0,255),rand(0,255));
imagesetpixel($image,$i_x,$i_y,$pixelcolor);
}
header('content-type:image/png');
imagepng($image);
imagedestroy($image);
?>
生成的样式演示:
在线演示:http://www.phzzy.org/temp/5do8/ex4_login.php
上述方法生成的图片颜色可能不够艳丽,导致用户看不清。为此,我们可以设定几个较艳丽的颜色并扩展 colorarrs 数组:
$colorarrs=array(
imagecolorallocate($image,255,255,255),
imagecolorallocate($image,0,0,0),
imagecolorallocate($image,0,70,0),
imagecolorallocate($image,92,0,12),
imagecolorallocate($image,0,0,128),
imagecolorallocate($image,233,10,216)
);
然后将第23行变为(第17行):
$fontcolor=$colorarrs[rand(1,count($colorarrs)-1)];
输出:
在线演示:http://www.phzzy.org/temp/5do8/ex5_login.php
例五:大点的比较cool的验证码
PS 的图像还是比较小的,有时候为了某些原因(个人站点为了玩cool,just我,商业站点玩风格,吸引用户,just google,后话),验证码不是局限于十几个px的限制,有时候完全可以整个2百多,没啥问题,这时候,一种方案是把前面生成的小图强制大点,可以不? 可以,但是,看起来不够光滑,这是事实,明显,宽带不再是最重要的问题,不说其他的,下面演示几个比较好看的生成方式:
<?php
session_start();
$width=600;
$height=100;
if($height < $width /6)
$height=$width / 4;
$sourcestrings="0123456789aqwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
//创建对象
$image=imagecreate($width,$height);
$white=imagecolorallocate($image,255,255,255);
imagefill($image,0,0,$white);
//加载字体库
$fonts= dirname(__FILE__);
putenv('"gdfontpath=".$fonts=.""');
$fontname='arial';
$font_size=floor($height / 2);
//得到字符串
unset($sessionval);
$strsize=rand(5,8);
for($i=0;$i<$strsize;$i++){
$i_temp=rand(1,62);
$sessionval .=$sourcestrings[$i_temp];
$x_i =$font_size + $i *$width / ($strsize+1);
$y_i = $height / 2;
$angle_i=rand(-120,120);
$fontcolor_a=imagecolorallocate($image,rand(0,255),rand(0,255),rand(0,255));
imageTTFText($image,$font_size,$angle_i,$x_i,$y_i,$fontcolor_a,$fontname,$sourcestrings[$i_temp]);
}
unset($_SESSION['cjjer']);
$_SESSION['cjjer'] = $sessionval;
//杂点数目
for($i=0;$i<$width * $height / 100;$i++)
{
$i_x=rand(0,$width);
$i_y=rand(0,$height);
imagesetpixel($image,$i_x,$i_y,imagecolorallocate($image,rand(0,255),rand(0,2550),rand(0,255)));
}
//发送对象
header('content-type:image/png');
imagepng($image);
imagedestroy($image);
?>
在线测试: http://www.phzzy.org/temp/5do8/ex6_login.php
解释性说明:
首先是宽和高,高太小会导致字迹不清。随机提取的字符集依然为:
$sourcestrings="0123456789aqwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
创建对象,并填充为白色背景:
$image=imagecreate($width,$height);
$white=imagecolorallocate($image,255,255,255);
imagefill($image,0,0,$white);
然后加载用于验证码的字体文件:
$fonts= dirname(__FILE__);//返回当前根目录,字体文件复制到这里,字体文件是*.ttf文件
putenv('"gdfontpath=".$fonts=.""');
$fontname='arial';
定义字符的高度,此处设置为高度的一半:
$font_size=floor($height / 2);
清除变量,随机设置要生成字符的个数:
unset($sessionval);
$strsize=rand(5,8);
循环逐个将字符写入图像:
获取本次循环的随机字符串,并追加到变量后以便写入session。
$i_temp=rand(1,62);
$sessionval .=$sourcestrings[$i_temp];
计算字符在图像中的位置(x和y坐标)。
$x_i =$font_size + $i *$width / ($strsize+1);
$y_i = $height / 2;
设置倾斜角度,模拟从正面看的视觉效果。
$angle_i=rand(-120,120);
随机生成字体颜色。
$fontcolor_a=imagecolorallocate($image,rand(0,255),rand(0,255),rand(0,255));
将文字写入到图像中。
imageTTFText($image,$font_size,$angle_i,$x_i,$y_i,$fontcolor_a,$fontname,$sourcestrings[$i_temp]);
若对该函数有疑问,请查阅相关资料,其用法非常直观。
将生成的验证码值写入session,供后续注册码验证使用:
unset($_SESSION['cjjer']);
$_SESSION['cjjer'] = $sessionval;
添加干扰杂点:
//杂点数目
for($i=0;$i<$width * $height / 100;$i++)
{
$i_x=rand(0,$width);
$i_y=rand(0,$height);
imagesetpixel($image,$i_x,$i_y,imagecolorallocate($image,rand(0,255),rand(0,2550),rand(0,255)));
}
将图像数据发送至浏览器头部:
header('content-type:image/png');//这行表明是png图像,可不写,默认可以输出的.但不是标准的图像头格式
imagepng($image);
imagedestroy($image);
你可以加载自定义字体库,通过设置旋转角度$angle_i=rand(-120,120)、字体高度$font_size=floor($height / 2)、字体颜色$fontcolor_a以及随机数个数:$strsize=rand(5,8)来定制验证码样式。
图片水印添加与缩略图生成技术
例六:给图片打上水印,生成缩列图
传统的ASP页面在处理水印和缩略图时较为繁琐,通常依赖第三方组件。而PHP可以轻松完成这些任务,正如预期,不到30行代码即可搞定一切,请看源程序:
<?php
$source="my.jpg";
$zoom=0.5;
$str='我是帅哥,你是MM么?';
$image=imagecreatefromjpeg($source);
$width=imagesx($image);
$height=imagesy($image);
$color_red=imagecolorallocate($image,111,0,0);//红色
$font=dirname(__FILE__). "//simsun.ttc";
$str=iconv('GB2312','UTF-8',$str);
$fontsize=30;
$angle=25;
$fromx=$width/5;
$fromy=$height/2;
imagettftext($image,$fontsize,$angle,$fromx,$fromy,$color_red,$font,$str);
$width_temp=imagesx($image) * $zoom;
$height_temp=imagesy($image) * $zoom;
$img=imagecreatetruecolor($width_temp,$height_temp);
imagecopyresized ($img,$image,0,0,0,0,$width_temp, $height_temp,$width,$height);
imagedestroy($image);
$file_zoomname="my_zoom_jpeg.jpg";
imagejpeg($img,$file_zoomname);
imagedestroy($img);
?>
原始图片:
生成的jpg图片:
原始图片70K,若生成gif格式文件约为18k,而png格式需76k,因此生成缩略图推荐使用jpeg格式以节省空间。
代码分析:
首先设置几个关键参数:
$source="my.jpg"; //源图片
$zoom=0.5; //缩放百分比
$str='我是帅哥,你是MM么?'; //水印的文字
装载源图(若不打水印则无需此步):
$image=imagecreatefromjpeg($source);
获取图像的长和宽大小:
$width=imagesx($image);
$height=imagesy($image);
设置水印字体,因涉及中文必须导入中文字体库,否则无法显示或乱码,同时需转换字符串编码。
$font=dirname(__FILE__). "//simsun.ttc";
$str=iconv('GB2312','UTF-8',$str);
设置起始点、字体大小及视角,然后写入字符串:
$fontsize=30;
$angle=25;
$fromx=$width/5;
$fromy=$height/2;
imagettftext($image,$fontsize,$angle,$fromx,$fromy,$color_red,$font,$str);
按照缩放比例要求生成新尺寸的图像对象:
$width_temp=imagesx($image) * $zoom;
$height_temp=imagesy($image) * $zoom;
$img=imagecreatetruecolor($width_temp,$height_temp);
将源图复制到新图中,gd库的imagecopyresized函数会自动处理缩放。
imagecopyresized ($img,$image,0,0,0,0,$width_temp, $height_temp,$width,$height);
生成小图片并清除旧对象:
imagedestroy($image);
$file_zoomname="my_zoom_jpeg.jpg";
imagejpeg($img,$file_zoomname);
imagedestroy($img);
生成缩略图和水印的核心技术要点即以上部分。