PHP图形图像处理之初识GD库

d=====( ̄▽ ̄*)bphp

 

引语html

 

php不单单局限于html的输出,还能够建立和操做各类各样的图像文件,如GIF、PNG、JPEG、WBMP、XBM等。浏览器

php还能够将图像流直接显示在浏览器中。服务器

要处理图像,就要用到php的GD库。函数

ps:确保php.ini文件中能够加载GD库。能够在php.ini文件中找到“;extension=php_gd2.dll”,将选项前的分号删除,保存,再重启Apache服务器便可。字体

 

步骤spa

 

在php中建立一个图像通常须要四个步骤:code

1.建立一个背景图像,之后的全部操做都是基于此背景。htm

2.在图像上绘图等操做。对象

3.输出最终图像。

4.销毁内存中的图像资源。

 

1.建立背景图像

 

下面的函数能够返回一个图像标识符,表明了一个宽为x_size像素、高为y_size像素的背景,默认为黑色。

 1 resource imagecreatetruecolor(int x_size , int y_size) 

在图像上绘图须要两个步骤:首先须要选择颜色。经过imagecolorallocate()函数建立颜色对象。

 1 int imagecolorallocate(resource image, int red, int green, int blue) 

而后将颜色绘制到图像上。

 1 bool imagefill(resource image, int x, int y, int color) 

imagefill()函数会在image图像的坐标(x,y)处用color颜色进行填充。

 

2.在图像上绘图

 

 1 bool iamgeline(resource image, int begin_x, int begin_y, int end_x, int end_y, int color) 

imageline()函数用color颜色在图像image中画出一条从(begin_x,begin_y)到(end_x,end_y)的线段。

 1 bool imagestring(resource image, int font, int begin_x, int begin_y, string s, int color ) 

imagestring()函数用color颜色将字符串s画到图像image的(begin_x,begin_y)处(这是字符串的左上角坐标)。若是font等于1,2,3,4或5,则使用内置字体,同时数字表明字体的粗细。

若是font字体不是内置的,则须要导入字体库后使用。

 

3.输出最终图像

 

建立图像之后就能够输出图形或者保存到文件中了,若是须要输出到浏览器中须要使用header()函数发送一个图形的报头“欺骗”浏览器,使它认为运行的php页面是一个图像。

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

发送数据报头之后,利用imagepng()函数输出图形。后面的filename可选,表明生成的图像文件的保存名称。

 1 bool image(resource image [, string filename]) 

 

4.销毁相关的内存资源

 

最后须要销毁图像占用的内存资源。

 1 bool imagedestroy(resource image) 

 

例子:

 1 <?php
 2 $width=300;                                              //图像宽度
 3 $height=200;                                             //图像高度
 4 $img=imagecreatetruecolor($width,$height);               //建立图像
 5 $white=imagecolorallocate($img,255,255,255);             //白色
 6 $black=imagecolorallocate($img,0,0,0);                   //黑色
 7 $red=imagecolorallocate($img,255,0,0);                   //红色
 8 $green=imagecolorallocate($img,0,255,0);                 //绿色
 9 $blue=imagecolorallocate($img,0,0,255);                  //蓝色
10 imagefill($img,0,0,$white);                              //将背景设置为白色
11 imageline($img,20,20,260,150,$red);                      //画出一条红色的线
12 imagestring($img,5,50,50,"hello,world!!",$blue);       //显示蓝色的文字
13 header("content-type: image/png");                    //输出图像的MIME类型
14 imagepng($img);                                          //输出一个PNG图像数据
15 imagedestroy($img);                                      //清空内存

  效果:

相关文章
相关标签/搜索