PHP基于GD库的图像处理方法
本示例详解PHP利用GD库进行图像处理的完整流程,供开发者参考与实践。
GD图像处理技术基础
需确保配置文件中启用extension=php_gd2.dll扩展。
画布的创建是图像处理的第一步。
画布属于资源型数据,代表可被操作的图像对象。
新建画布有两种主要方式。
使用imageCreate(width,height)可创建基于调色板的画布。
使用imageCreateTrueColor(width,height)可创建真彩色画布。
除了新建,也可基于现有图片文件创建画布以进行读取和修改。
相关函数包括imageCreateFromJPEG(url)、imageCreateFromPNG(url)及imageCreateFromGIF(url)。
对画布的操作涉及多个步骤。
若需在画布上使用特定颜色,必须先将其分配到画布资源中。
语法为(颜色标识) = imageColorAllocate(img,r,g,b),其中r,g,b为红绿蓝分量。
填充画布区域也是常见操作。
使用imageFill(img,x,y,颜色标识)可在指定坐标(x,y)处填充颜色。
处理完成后,需要将画布输出。
第一种方式是保存为图片文件。
第二种是直接输出到浏览器,此时需调用header("Content-type:image/png;")告知浏览器内容为图片。
imagePNG(img[,url])
imageJPEG()
imageGIF()
图像处理结束后,应及时销毁画布资源以释放内存。
调用imageDestroy(img)即可销毁指定的图像资源。
<?php
header('content-type:image/png');
$img = imagecreate(300,300);
$color = imagecolorallocate($img,223,22,44);
imagefill($img,3,3,$color);
imagepng($img);
imagedestroy();
?>
上述基础操作的运行效果如图所示。

利用GD库可以进一步实现动态验证码功能。
<?php
header('content-type:image/png');
$code = '123456789abcdefghijklmnpqrstuvwxvz';
$length = strlen($code);
$print = '';
for($i=0; $i<4; $i++){
$print.=$code[mt_rand(0,$length-1)];
}
// echo $print;
$img = imagecreatefrompng('./str.png');
$color = mt_rand(0,1)==1?imagecolorallocate($img,0,0,0):imagecolorallocate($img,255,255,255);
//图片大小
$img_width = imagesx($img);
$img_height = imagesy($img);
//字体大小
$font = 5;
$font_width = imagefontwidth($font);
$font_height = imagefontheight($font);
$fin_w = ($img_width-$font_width*4)/2;
$fin_h = ($img_height-$font_height)/2;
imagestring($img,$font,$fin_w,$fin_h,$print,$color);
imagepng($img);
imagedestroy($img);
?>
验证码生成的运行效果如图所示。

<?php
session_start();
$im=imagecreatetruecolor(80,30);
$str="";
for ($i=0;$i<4;$i++){
$str.=dechex(rand(0,15));
}
$_SESSION['code']=$str;
$white=imagecolorallocate($im,255,255,255);
imagestring($im,rand(2,5),rand(0,70),rand(0,10),$str,$white);
//imagettftext($im,rand(0,5),rand(0,180),rand(0,100),rand(0,10),$white,"simhei.ttf",$str);
for($i=0;$i<20;$i++){
$color=imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));
imageline($im,rand(0,90),rand(0,20),rand(0,100),rand(0,100),$color);
}
header("content-type:image/png");
imagepng($im);
imagedestroy($im);
?>
关键注意点:在输出图片之前和之后,代码中不能有任何额外的HTML或文本输出,否则会导致图片损坏。
希望本文所述内容能对大家的PHP程序设计工作有所帮助。