本文主要和大家分享php图像图形的操作gd库的使用基础教程,希望能帮助到大家。
1>gd库简介
gd指的是graphic device,php的gd库是用来处理图形的扩展库,通过gd库提供的一系列api,可以对图像进行处理或者直接生成新的图片。
php除了能进行文本处理以外,通过gd库,可以对jpg、png、gif、swf等图片进行处理。gd库常用在图片加水印,验证码生成等方面。
php默认已经集成了gd库,只需要在安装的时候开启就行。
创建图像的一般流程
设定标头,告诉浏览器你要生成的mime类型
创建一个图像区域,以后的操作都将基于此图像区域
在空白图像区域绘制填充背景
在背景上绘制图形轮廓输入文本
输出最终图形
清除所有资源
其他页面调用
header(content-type: image/png);$img=imagecreatetruecolor(100, 100);$red=imagecolorallocate($img, 0xff, 0x00, 0x00);
imagefill($img, 0, 0, $red);
imagepng($img);
imagedestroy($img);
绘制线条
imageline()
语法:imageline(
sx,
ex,
col);
绘制圆
imagearc()
语法:imagearc (
cx ,
w ,
startangle,
color )
$img = imagecreatetruecolor(200, 200);// 分配颜色$red = imagecolorallocate($img, 255, 0, 0);$white = imagecolorallocate($img, 255, 255, 255);//背景填充白色
imagefill($img,0,0,$white);// 画一个红色的圆
imagearc($img, 100, 100, 150, 150, 0, 360, $red);
imagepng($img);// 释放内存
imagedestroy($img);
绘制矩形
imagerectangle()
语法:imagerectangle (
x1 ,
x2 ,
col)
$img = imagecreatetruecolor(200, 200);// 分配颜色$red = imagecolorallocate($img, 255, 0, 0);$white = imagecolorallocate($img, 255, 255, 255);
imagefill($img,0,0,$white);// 画一个红色的矩形
imagerectangle ($img,50,50,100 ,100 ,$red);
imagepng($img);// 释放内存
imagedestroy($img);
绘制文字
语法1:imagestring (
font ,
y ,
col )
语法2:imagettftext(
size,
x,
color,
text)
header(content-type: image/png);//imagestring字体大小设置不了$img = imagecreatetruecolor(100, 100);$red = imagecolorallocate($img, 0xff, 0x00, 0x00);
imagestring($img, 5, 10, 10, hello world, $red);
imagepng($img);
imagedestroy($img);$img1=imagecreatetruecolor(200,200);$red=imagecolorallocate($img1,255,0,0);$white=imagecolorallocate($img1,255,255,255);
imagefill($img1,0,0,$red);$font=c:\windows\fonts\simhei.ttf;
imagettftext($img1,23,0,100,100,$white,$font,你好吗);
imagepng($img1);
imagedestroy($img1);
绘制噪点
语法:imagesetpixel(
x,
col)
//绘制10个噪点for($i=0;$i<10;$i++) {
imagesetpixel($img, rand(0, 100) , rand(0, 100) , $black);
imagesetpixel($img, rand(0, 100) , rand(0, 100) , $green);
}
输出图像文件
通过imagepng可以直接输出图像到浏览器,通过指定路径参数将图像保存到文件中
1. imagepng()
意义:将图片保存成png格式
语法:imagepng(
filename)
2. imagejpeg()
意义:将图片保存成jpeg格式
语法:imagepng(filename,$quality)
3. imagegif()
意义:将图片保存成gif格式
语法:imagegif(filename)案例:
1. 随机产生验证码(php)
2. 给图片添加水印
相关推荐:
gd库生成水印乱码的解决办法
详解php如何使用gd库完成验证码效果教程
什么是gd库?在php中加载gd库的具体介绍
以上就是php图像图形的操作gd库的使用基础教程的详细内容。