PHP编程
图像
介绍
PHP 可以动态地创建和修改图像,例如使用自带的 GD 图形库(从 PHP 3.0 版本起默认包含)。
创建一个新图像通常需要经过以下几个步骤:
- 将新图像或现有图像加载到内存中。
- 可选的加载颜色。
- 可选的修改组件(如绘制线条、点、填充、添加文本等)。
- 通过在头部中设置图像类型来显示图像。
- 释放内存。
创建新图像
要从零开始创建一个图像,可以使用以下函数:
imagecreatetruecolor($width, $height)
它在内存中创建一个新的图像,图像的宽度和高度是以像素为单位定义的,并返回对该新图像的引用。
还有另一个函数可以创建图像,但不推荐使用,因为它的颜色幅度较差:
imagecreate($width, $height)
要加载一个已经保存在磁盘上的图像,可以使用:
imagecreatefrom<type>($path)
例如:
$img = imagecreatefrompng('image.png');
其他函数包括:
imagecreatefromstring($text)
它通过文本格式(作为参数指定)创建图像。
如果出现错误,这些函数会返回 false
。
操作颜色
要分配一种颜色,必须定义 RGB 参数:
$color = imagecolorallocate($image, $r, $g, $b);
要定义 PNG 图像中的透明度:
imagecolortransparent($image, $color);
其中 $color
是 imagecolorallocate
返回的颜色值。
还可以通过以下函数设置透明度,透明度范围是 0 到 127(其中 127 代表完全透明):
imagecolorallocatealpha($image, $r, $g, $b, $transparency);
备注:第一个分配的颜色定义了整个图像的背景。
一旦图像创建并上色,就可以对其进行以下操作:
绘制形状
- 绘制一个像素:
imagesetpixel($image, x, y, $color);
- 在两个点之间绘制一条线:
imageline($image, x1, y1, x2, y2, $color);
- 根据对角线创建矩形:
imagerectangle($image, x1, y1, x2, y2, $color);
- 根据中心点、宽度和高度绘制椭圆:
imageellipse($image, x, y, h, l, $color);
或者根据角度绘制弧形(按顺时针编号):
imagearc($image, x, y, h, l, angle1, angle2, $color);
重新处理现有像素
最常用的处理图像(如照片)函数是 imagecopyresized
,它允许将一个矩形区域复制并粘贴到另一个图像中。示例:
imagecopyresized($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
其中:
$src_image
是源图像;$dst_image
是目标图像;$dst_x, $dst_y
是目标图像的坐标;$src_x, $src_y
是源图像的坐标,从左上角开始;$dst_w, $dst_h, $src_w, $src_h
是源和目标矩形的宽度和高度。
如果 dst_w
等于 src_w
,dst_h
等于 src_h
,那么图像的矩形区域将保持原大小。反之,则会拉伸或缩放图像。
imagecopyresampled
函数与 imagecopyresized
函数接受相同的参数,但在调整大小时质量更高。
此外,还有 imagefilter
函数,允许应用多种效果,如灰度、浮雕或重新着色。
打印输出
可以通过 header
函数指定图像的格式("png"、"jpeg" 或 "gif"),使用 Content-type
来指定类型(默认为 text/html
):
header("Content-type: image/<type>");
然后,根据图像类型,使用以下函数之一来显示图像:imagepng
、imagejpeg
或 imagegif
。
最后,使用 imagedestroy($image)
来释放内存。这个步骤是可选的,但对于大型图像,强烈建议使用。
示例
以下代码在浏览器中显示一个 50 像素的红色方块,放置在一个 100 像素的黑色方块中:
$image = imagecreatetruecolor(100, 100);
$color = imagecolorallocate($image, 255, 0, 0);
imagefilledrectangle($image, 0, 0, 50, 50, $color);
header("Content-type: image/png");
imagepng($image);
imagedestroy($image);