PHP创建图像

来源:百度文库 编辑:神马文学网 时间:2024/10/02 22:29:10
From: http://hi.baidu.com/vincent_1984
今天来说说PHP如何创建图像。大家先来看一段代码

$im = @imagecreate (150, 100)

      or die ("没有安装GD图象库");

//设置背景颜色

$background_color = imagecolorallocate ($im, 255, 255, 255);

//设置字体颜色

$text_color = imagecolorallocate ($im, 233, 14, 91);

//将字符串放到图象上

imagestring ($im, 3, 5, 5,     "A Simple Text String", $text_color);

//输出图象

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

imagepng ($im);


imagedestroy ($im);

基本步骤

首先建立一个图像标尺图(确定图像的大小)

建立空白的背景:Imgcreatetruecolor($width,$height)

传递图像的宽度和高度。
另一种方法读入一个已有的图像文件。

ImageCreateFromGif(string filename)

ImageCreateFromPNG(string filename)

ImagecreateFromjpeg(string filename)

失败时返回一个空字符串,并且输出一条错误信息

接下来是在图像上绘图或输出文本。需要分两个步骤来完成。

第一步是选择颜色ImageColorAllocate(resource image,int red,int green,int blue)

第二步是文本的信息 ImageString(resource image,nit font,nit x, int y,string s,int col)

用col颜色将字符串s画到image所代表的图像的(x , y)坐标处(这是字符串左上角坐标,整幅图像的左上角为(0 , 0))。Font是1,2,3,4或5.

                             

现在可以将一个图像直接输出到浏览器或者一个文件,也分两步来完成。

第一步需要告诉web浏览器输出的是图像而不是文本或HTML,通过调用Header()函数指定图像的MINE类型来完成:header(“Content-type:image/png(jpeg/gif)”)

在发送标题数据后,输出到浏览器。Bool Imagepng(resource image [,string filename])

如果用filename给出了文件名则将其输出到该文件。

Imagejpeg(resource image[,string filename[, int quality]])

Quality范围从0(质量最差,文件最小)到100(质量最佳,文件最大)

当完成图像处理的时候,应该销毁图像标识符将占用的资源返回给服务器。Imagedestroy()