1. PHP图片处理基础
1.1 安装GD库
打开你的php.ini文件,找到以下行并取消注释:
extension=gd
然后重启你的服务器以使更改生效。
1.2 安装Imagick扩展
如果你选择使用Imagick,可以通过Composer来安装:
composer require php-imagine/imagine
2. 创建图片资源
$width = 100;
$height = 100;
$image = imagecreatetruecolor($width, $height);
这里,imagecreatetruecolor函数创建了一个真彩色画布。
3. 分配颜色并填充画布
在创建画布后,你可以分配颜色并填充画布:
$color = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $color);
这里,imagecolorallocate函数用于分配颜色,imagefill函数用于填充画布。
4. 输出图片
header('Content-Type: image/png');
imagepng($image);
5. 处理和显示现有图片
$image = imagecreatefromjpeg('path/to/image.jpg');
6. 优化图片流显示
6.1 图片压缩
imageinterlace($image, 1);
imagefilter($image, IMG_FILTER_CONTRAST);
6.2 缓存图片
$cachePath = 'cache/' . md5($imagePath) . '.jpg';
if (!file_exists($cachePath)) {
// 处理图片并保存到缓存
imagejpeg($image, $cachePath);
}
6.3 异步加载
<img src="path/to/image.jpg" alt="Description" class="lazyload">