引入gd库
打开 php目录下的php.ini,在php.ini中搜索gd,搜索相应的扩展文件,并取消行首的 ";"
重启apache,在php文件中打印<?php phpinfo() ?>可以查看是否开启GD库
GD库画图流程
// 1) 创建画布 imagecreatetruecolor( 宽 , 高 );
$im = imagecreatetruecolor(300,200);
// 2) 创建颜料 imagecolorallocate( 画布 , 红 , 绿 , 蓝 )
$red = imagecolorallocate($im , 255 , 0 ,0);
//填充背景图片
imagefill($im,x轴,y轴,$blue);
// 3) 画椭圆 imageellipse( 画布 , 圆心 x 坐标 , 圆心 y 坐标 , 宽 , 高 , 边框颜色 )
imageellipse($im,150,100,300,200,$red);
// 4) 输出 imagepng( 画布 [, 保存位置 ]),imagejpeg(),imagegif()
imagepng($im , './test1.png');
// 5) 销毁画面 imagedestroy( 画布 )
imagedestroy($im);
验证码
<?php
//随机数函数
function randStr($length){
$str = str_shuffle('abcdefghijkmnprstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789');
$str = substr($str,0,$length);
return $str;
}
//创建画布
$im = imagecreatetruecolor(100,50);
//创建颜色
$red = imagecolorallocate($im,255,0,0);
$gray = imagecolorallocate($im,200,200,200);
//填充颜色
imagefill($im,0,0,$gray);
//在水平位置画一行字符串
imagestring($im,5,10,20,randStr(6),$red);
//输出画布
imagepng($im,'./test02.png');
//销毁画布
imagedestroy($im);
?>
缩略图与水印
<?php
//水印
//创建,获取一个新图像
$big = imagecreatefrompng('./test01.png');
$small = imagecreatefrompng('./test02.png');
//获取图像宽,高
list($wb,$hb) = getimagesize('./test01.png');
list($ws,$hs) = getimagesize('./test02.png');
//将小图粘贴到大图上,并透明
//imagecopymerge(原图,水印,原图x坐标,原图y坐标,水印x坐标,水印y坐标,水印宽,水印高,透明度)
imagecopymerge($big,$small,0,0,0,0,$ws,$hs,40);
//输出图像
imagepng($big,'./test03.png');
//销毁图像
imagedestroy($big);
imagedestroy($small);
?>
<?php
//缩略图
$pic = './test03.png';
//获取原图宽高
list($w,$h) = getimagesize($pic);
//获取原图
$big = imagecreatefrompng($pic);
//创建新画布
$small = imagecreatetruecolor($w/2,$h/2);
//将原图,按比例缩放到新画布上
imagecopyresampled($small,$big,0,0,0,0,$w/2,$h/2,$w,$h);
//输出缩略图
imagepng($small,'./test05.png');
//销毁图像
imagedestroy($big);
imagedestroy($small);
?>