PHP脚本的8个技巧(4)动态创建图象
http://tech.ddvip.com 2007年08月26日 社区交流
内容摘要:PHP脚本的8个技巧
使用ImageCreate()创建一个变量存放空白图像。该函数需要以像素为单位的图像大小。格式是ImageCreate(x_size, y_size),对250-X-250像素的图像而言,用法如下:
$newImg = ImageCreate(250,250);
因为你的图像现在还是空白,所以你还要设法用某些色彩填满它,但是,首先你需要按照颜色的RGB值为每种颜色分配名字,这要用到ImageColorAllocate()函数。函数的格式是ImageColorAllocate([image], [red], [green], [blue])。如果是天蓝色,具体代码如下:
$skyblue = ImageColorAllocate($newImg,136,193,255);
接着,你需要调用ImageFill()函数为图像填充以上的颜色。ImageFill(),函数有好几个版本,比如ImageFillRectangle(), ImageFillPolygon()等等。为简单起见,我们就采用ImageFill()函数进行颜色填充,格式如下:
ImageFill([image], [start x point], [start y point], [color])
ImageFill($newImg,0,0,$skyblue);最后,你创建了图像并破坏图像流以释放内存:
ImagePNG($newImg);
ImageDestroy($newImg); ?>具体的代码看起来很像下面的样子:
<? header ("Content-type: image/png");
$newImg = ImageCreate(250,250);
$skyblue = ImageColorAllocate($newImg,136,193,255);
ImageFill($newImg,0,0,$skyblue);
ImagePNG($newImg);
ImageDestroy($newImg);
?>如果你调用这个脚本skyblue.php 并用自己的浏览器访问它,你就会看到一个250-X-250像素大的蓝色PNG图像。
你还可以用图像创建函数处理图像,比如创建大型图像的缩微图等。
假设你打算为某个图片制作一个35-X-35像素大小的缩微图。你要做到就是创建一个新的35 X 35 像素大小的图像;制造出一个包含其原始图像内容的图像流;然后改变原始图像的大小,并把它放到新的空白图像中去。
用来达到以上目的的关键函数就是ImageCopyResized(),,该函数的格式如下所示:ImageCopyResized([new image handle],[original image handle],[new image X], [new Image Y], [original image X], [original image Y], [new image X], [new image Y], [original image X], [original image Y]);
以下是代码注释。
<? /* send a header so that the browser knows the content-type of the file */
header("Content-type: image/png");
/* set up variables to hold the height and width of your new image */
$newWidth = 35;
$newHeight = 35;
/* create a blank, new image of the given new height and width */
$newImg = ImageCreate($newWidth,$newHeight);
/* get the data from the original, large image */
$origImg = ImageCreateFromPNG("test.png");
/* copy the resized image. Use the ImageSX() and ImageSY functions to get the x and y sizes of the orginal image. */
ImageCopyResized($newImg,$origImg,0,0,0,0,$newWidth,$newHeight,ImageSX($origImg),ImageSY($origImg));
/* create final image and free up the memory */
ImagePNG($newImg);
ImageDestroy($newImg); ?>如果你调用了以上脚本resized.php 并用自己的浏览器访问它,你应该能看到一个35-X-35像素大小的缩微PNG图。
责编:豆豆技术应用
- php 正则表达式
- php 入门教程
- php 安装配置
- php 函数专题
- php 函数大全(EN)
- php 5.0 中文手册
- php 4.0 中文手册
- php 程序编码规范标准
- php 常见错误
- php 中文乱码
- php Apache 安装配置
- linux php 安装配置
- windows php 安装配置
- php 十天入门教程
- php 学习笔记
- php smarty 教程
- php 分页专题
- php 类
- php 变量
- php 常量
- php 数组
- php 脚本
- php 入门实例
- php 字符串
- php.ini 配置
- php xml 专题
- php session 教程
- php 对象模型
- 更多php专题……