php gd库的用法
2022-12-02 09:01:16
85
{{single.collect_count}}

php gd库的使用方法:首先创建一个PHP示例文件;然后用GD库中的“imagecreatetruecolor”方法创建一块空白图片;最后通过imageline绘制一个简单的线条即可。

php入门到就业线上直播课:进入学习
Apipost = Postman + Swagger + Mock + Jmeter 超好用的API调试工具:点击使用

本文操作环境:windows7系统、PHP7.1版,DELL G3电脑

php gd库的用法

在php中需要图像处理的地方GD库会发挥重要的作用,php可以创建并处理包括GIF,PNG,JPEG,WBMP以及XPM在内的多种图像格式,简单的举几个例子:

1、用GD库会创建一块空白图片,然后绘制一个简单的线条

$img=imagecreatetruecolor(100, 100);//创建空白图片$red=imagecolorallocate($img, 0xFF, 0x00, 0x00);//创建画笔imageline($img,0,0,100,100,$red);//绘制线条//输出图像到页面header("content-type: image/png");imagepng($img);//释放图片资源imagedestroy($img);
登录后复制

那么现在就在默认黑色的背景上画了一个红色的线段,坐标从(0,0)到(100,100)

效果就如下图:

2、绘制字符串

$img = imagecreatetruecolor(100, 100);$red = imagecolorallocate($img, 0xFF, 0x00, 0x00);//开始绘制字符串imagestring($img,5,0,13,"zengzhiying",$red);header("content-type: image/png");imagepng($img);imagejpeg($img,'img.jpg',80);//输出图片到文件并设置压缩参数为80imagedestroy($img);
登录后复制

代码第7行代码作用是将图片保存到文件,直接可以打开,也可以用imagepng()函数保存为PNG格式的图片

3、生成数字验证码【推荐学习:《PHP视频教程》】

$img = imagecreatetruecolor(100, 40);$black = imagecolorallocate($img, 0x00, 0x00, 0x00);$green = imagecolorallocate($img, 0x00, 0xFF, 0x00);$white = imagecolorallocate($img, 0xFF, 0xFF, 0xFF);imagefill($img,0,0,$white);//绘制底色为白色//绘制随机的验证码$code = '';for($i = 0; $i < 4; $i++) {$code .= rand(0, 9);}imagestring($img, 6, 13, 10, $code, $black);//加入噪点干扰for($i=0;$i<50;$i++) {imagesetpixel($img, rand(0, 100) , rand(0, 100) , $black);imagesetpixel($img, rand(0, 100) , rand(0, 100) , $green);}//输出验证码header("content-type: image/png");imagepng($img);imagedestroy($img);
登录后复制

这样就生成了4位随机数字验证码,并且有黑色和绿色两种颜色的点干扰,当然这是最简陋的一个验证码了,在这里只是演示大致过程,效果如下图:

4、给图片添加水印

$filename = 'tmp.jpg';$logofile='logo.png';$im = imagecreatefromjpeg($filename);$logo = imagecreatefrompng($logofile);$size = getimagesize($logofile);imagecopy($im, $logo, 15, 15, 0, 0, $size[0], $size[1]);header("content-type: image/jpeg");imagejpeg($im);imagedestroy($im);
登录后复制

imagecopy()就是添加水印的函数,里面的参数可以自己调整,做出来更好的水印

以上就是GD库的简单应用了,也可以把代码做成一个函数来使用。

以上就是php gd库的用法的详细内容,更多请关注php中文网其它相关文章!

回帖
全部回帖({{commentCount}})
{{item.user.nickname}} {{item.user.group_title}} {{item.friend_time}}
{{item.content}}
{{item.comment_content_show ? '取消' : '回复'}} 删除
回帖
{{reply.user.nickname}} {{reply.user.group_title}} {{reply.friend_time}}
{{reply.content}}
{{reply.comment_content_show ? '取消' : '回复'}} 删除
回帖
收起
没有更多啦~
{{commentLoading ? '加载中...' : '查看更多评论'}}