官方文档:http://image.intervention.io
1、安装
安装 Intervention Image 之前,需要确保 PHP 版本 >=5.4 并且安装了 Fileinfo 扩展,以及 GD 库(>=2.0)或者 Imagick 扩展(>=6.5.7)。
我们使用 Composer 在命令行安装最新版本的 Intervention Image:
composer require intervention/image
2、集成到 Laravel
前面已经提到,Intervention Image 提供了相应的服务提供者和门面以便集成到 Laravel 应用。
安装好 Intervention Image 后,打开 config/app.php,注册如下服务提供者到 $providers 数组:
Intervention\Image\ImageServiceProvider::class
然后添加如下门面到 $aliaes 数组:
'Image' => Intervention\Image\Facades\Image::class
3、配置
默认情况下,Intervention Image 使用 PHP 的 GD 库扩展处理所有图片,如果你想要切换到 Imagick,你可以将配置文件拉到应用中:
php artisan vendor:publish --provider="Intervention\Image\ImageServiceProviderLaravel5"
这样对应的配置文件会被拷贝到 config/image.php,这样你可以在该配置文件中修改图片处理驱动配置。
4、用法示例
1、剪切图片并保存
$image = Image::make('images/demo.png');
// 修改指定图片的大小
$image->resize(200, 200);
// 插入水印, 水印位置在原图片的右下角, 距离下边距 10 像素, 距离右边距 15 像素
$image->insert('images/watermark.png', 'bottom-right', 15, 10);
// 保存图片,为空直接覆盖
$image->save('images/new_demo.png');
/* 上面的逻辑可以通过链式表达式搞定 */
$image = Image::make('images/demo.png')->resize(200, 200)->insert('images/watermark.png', 'bottom-right', 15, 10)->save('images/new_demo.png');
2、比例剪切
// 限制图片最大宽度为1000px
$image = Image::make($file_path);
if ($image->width() > 1000) {
$image->resize(1000, null, function ($constraint) {
$constraint->aspectRatio();
});
$image->save();
}