图像处理
网站开发中需要经常处理图片,如课程缩略图,用户头像等,使用PHP处理图像非常简单。
配置环境
PHP中图像处理需要GD库的支持。
在windows系统中修改php.ini文件,删除 extension=php_gd2.dll 前面的;
开启图像处理支持。
centos中使用 yum install php-gd*
ubuntu系统中使用 apt-get install php7.3-gd
检测GD库是否加载
$has = extension_loaded('GD');
var_dump($has);
使用方法
PHP创建图像步骤
- 发送HTTP头信息,声明内容为图像
- 创建画布
- 创建绘图所需要的颜色
- 绘图(填充画布、画圆、画方块、画线条、画布上写字)
- 输出图像
- 释放画布资源
头信息
通过header() 函数告诉浏览器,输出的是一个图像而不是文本或HTML,这样浏览器就可以正常显示图像了。
- header('Content-type:image/gif');
- header('Content-type:image/jpeg');
- header('Content-type:image/png');
header('Content-type:image/jpeg');
readfile('user.jpeg');
创建画布
imageCreateTrueColor(width,height)
- 传入的两个参数分别为画布的宽和高,在绘图时超出宽高的部分将不予显示,且此尺寸即为生成图片文件时的尺寸。
- 返回值为资源类型。
设置颜色
imageColorAllocate(img_resource,R,G,B)
- 颜色从属于某个图像资源而存在。
- 颜色实际上是一个整形数值。
- 颜色的后三个参数需传入值的范围是0~255
填充颜色
imageFill(img_resource,x,y,color)
- (x,y)表示从哪个点开始填充颜色的坐标
- 不填充画布的话,默认是黑色
header('Content-type:image/jpeg');
$res = imagecreatetruecolor(1000, 500);
$red = imagecolorallocate($res, 255, 0, 0);
imagefill($res, 0, 0, $red);
imagejpeg($res);
绘制矩形
绘制空心矩形
- imageRectangle(img_res,x1,y1,x2,y2,color)
header('Content-type:image/jpeg');
$res = imagecreatetruecolor(1000, 500);
$red = imagecolorallocate($res, 255, 0, 0);
$green = imagecolorallocate($res, 0, 255, 0);
imagefill($res, 0, 0, $red);
imagerectangle($res, 100, 100, 200, 200, $green);
imagejpeg($res);
绘制填充好的实心矩形
imageFilledRectangle (img_res,x1,y1,x2,y2,color)
- (x1,y1)为左上角坐标, (x2,y2)为右下角坐标
header('Content-type:image/jpeg');
$res = imagecreatetruecolor(1000, 500);
$red = imagecolorallocate($res, 255, 0, 0);
$green = imagecolorallocate($res, 0, 255, 0);
imagefill($res, 0, 0, $red);
imagefilledrectangle($res, 100, 100, 300, 300, $green);
imagejpeg($res);
绘制圆形
绘制空心圆形
- imageEllipse(img_res,x,y,w,h,color)
绘制填充好的实心圆
- imageFilledEllipse(img_res,x,y,w,h,color)
说明:
- (x,y)为圆心坐标。 w为宽度,h为高度