php图形图像函数的运用-验证码

来源:互联网 发布:ubuntu 改用户名 编辑:程序博客网 时间:2024/06/01 09:16

使用php图形图像

1. PHP图形图像处理之初识GD库
php不仅仅局限于html的输出,还可以创建和操作各种各样的图像文件,如GIF、PNG、JPEG等,php还可以将图像流直接显示在浏览器中,要处理图像,就要用到php的GD库。
确保php.ini文件中可以加载GD库。可以在php.ini文件中找到“;extension=php_gd2.dll”,将选项前的分号删除,保存,再重启Apache服务器即可。


2.在php中创建一个图像一般需要四个步骤:
1.创建一个背景图像,以后的所有操作都是基于此背景。
2.在图像上绘图等操作。
3.输出最终图像。
4.销毁内存中的图像资源。


3.运用图形图像函数--验证码

创建背景图像

1.resource imagecreatetruecolor ( int x_size, int y_size )

新建一个真彩色图像

返回一个图像标识符,代表了一个宽为x_size像素、高为y_size像素的背景,默认为黑色

$im = imagecreatetruecolor(100,50)or die("cannot create image");

2.int imagecolorallocate ( resource image, int red, int green, int blue )

创建颜色对象

$background = imagecolorallocate($im,255,0,0);
$white = imagecolorallocate($im,255,255,255);
$black = imagecolorallocate($im,0,0,0);

3.bool imagefill ( resource image, int x, int y, int color )

颜色绘制到图像上

imagefill($im,0,0,$background);

在图像上绘图操作

1.bool imageline ( resource image, int x1, int y1, int x2, int y2, int color )
画一条线段
imageline() 用 color 颜色在图像 image 中从坐标 x1,y1 到 x2,y2画一条线段,(图像左上角为 0, 0)

imageline($im,0,0,50,50,$black);

 2.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,则使用内置字体。如果font字体不是内置的,
则需要导入字体库后使用。

imagestring($im,5,10,10,'hello php!',$white);

输出最终图像

bool imagepng ( resource image [, string filename] )

创建图像以后就可以输出图形或者保存到文件中了,如果需要输出到浏览器中需要使用header()函数发送一个图形的报头“欺骗”浏览器,使它认为运行的php页面是一个图像。
header("Content-type: image/png");
发送数据报头以后,利用imagepng()函数输出图形。后面的filename可选,代表生成的图像文件的保存名称

header("Content-type: image/png");

imagepng($im);

销毁相关的内存资源

bool imagedestroy ( resource image )

imagedestroy() 释放与 image 关联的内存。image 是由图像创建函数返回的图像标识符

imagedestroy($im);

0 0