图像处理
简介
Laravel 提供流畅的图像处理 API,可用框架中一贯富有表现力的约定来调整大小、裁剪、编码与存储图像。Laravel 的图像功能由 Intervention Image 驱动,并支持 GD 与 Imagick PHP 扩展。
在处理上传文件、存储于 Laravel 文件系统磁盘 上的文件、本地文件、远程 URL 或原始图像字节时,该图像 API 都很有用:
use Illuminate\Support\Facades\Image;
$path = Image::fromStorage('avatars/photo.jpg', 'public')
->cover(400, 400)
->toWebp()
->quality(80)
->storePublicly('avatars', 'public');WARNING
图像处理可能占用大量 CPU 与内存。对于较大的图像处理任务,建议在队列任务中执行,而不是在接收上传的 HTTP 请求中进行。
安装
使用 Laravel 的图像处理功能之前,请先通过 Composer 安装 Intervention Image 包:
composer require intervention/image:^4.0还应确保 PHP 已安装 GD 或 Imagick 扩展,具体取决于应用将使用的驱动。
配置
Laravel 的图像配置文件位于 config/images.php。若应用尚无 images 配置文件,可使用 config:publish Artisan 命令发布:
php artisan config:publish images图像配置文件允许你指定应用的默认图像驱动。也可通过 IMAGE_DRIVER 环境变量指定默认驱动。支持的驱动为 gd 与 imagick:
IMAGE_DRIVER=imagick读取图像
Image Facade 提供多种从常见来源读取图像的方法。图像内容采用惰性加载,因此通常在图像被处理或请求其字节时才会读取来源。
上传文件
可使用 image 方法从传入请求中获取上传的图像。该方法会为上传文件返回 Illuminate\Image\Image 实例;若文件不存在则返回 null:
use Illuminate\Http\Request;
Route::post('/avatar', function (Request $request) {
$request->validate(['avatar' => ['required', 'image']]);
$path = $request->image('avatar')
->cover(400, 400)
->toWebp()
->storePublicly('avatars', 'public');
// ...
});或者,可使用 fromUpload 方法从 Illuminate\Http\UploadedFile 实例创建图像实例:
use Illuminate\Support\Facades\Image;
$image = Image::fromUpload($request->file('avatar'));当图像由上传文件创建时,可使用 file 方法获取底层上传文件:
$file = $image->file();存储文件
可使用 fromStorage 方法,从应用某个文件系统磁盘上存储的文件创建图像实例。第一个参数为文件路径,第二个参数为磁盘名称:
use Illuminate\Support\Facades\Image;
$image = Image::fromStorage('avatars/photo.jpg', disk: 'public');也可直接从文件系统磁盘实例使用 image 方法创建图像实例:
use Illuminate\Support\Facades\Storage;
$image = Storage::disk('public')->image('avatars/photo.jpg');其他来源
Image Facade 还包含从原始字节、本地文件路径、远程 URL 以及 Base64 编码字符串创建图像实例的方法:
use Illuminate\Support\Facades\Image;
$image = Image::fromBytes($contents);
$image = Image::fromBase64($base64);
$image = Image::fromPath(storage_path('app/avatars/photo.jpg'));
$image = Image::fromUrl('https://example.com/photo.jpg');处理图像
图像实例是不可变的。每个处理方法都会返回一个新的图像实例,并将变换追加到其处理管道中,从而支持流畅链式调用:
$image = $request->image('avatar')
->orient()
->cover(400, 400)
->sharpen(10);变换按加入图像管道的顺序处理,图像仅在最后编码一次。
调整图像大小
resize 方法将图像调整为给定尺寸。可同时提供宽与高,也可使用命名参数只提供一个维度:
$image = $image->resize(800, 600);
$image = $image->resize(width: 800);
$image = $image->resize(height: 600);scale 方法按比例缩小图像,使其适应给定尺寸。该方法不会放大图像:
$image = $image->scale(800, 600);
$image = $image->scale(width: 800);
$image = $image->scale(height: 600);cover 方法会调整大小并裁剪图像,使其完全覆盖给定尺寸:
$image = $image->cover(400, 400);contain 方法会将图像调整为适应给定尺寸,同时保留整张图像。如有必要,空白区域将用可选的背景色填充:
$image = $image->contain(400, 400);
$image = $image->contain(400, 400, '#ffffff');
$image = $image->contain(400, 400, 'dominant');可将背景色指定为 dominant,用图像的主色填充空白区域。
可使用 crop 方法裁剪图像。前两个参数为期望的宽与高,可选的第三、第四个参数指定裁剪的 x 与 y 坐标:
$image = $image->crop(300, 200);
$image = $image->crop(300, 200, x: 50, y: 25);其他变换
Laravel 还提供多种其他图像变换方法:
$image = $image->orient();
$image = $image->rotate(90);
$image = $image->rotate(90, '#ffffff');
$image = $image->rotate(90, 'dominant');
$image = $image->blur(5);
$image = $image->grayscale();
$image = $image->sharpen(10);
$image = $image->flipVertically();
$image = $image->flipHorizontally();orient 方法根据 EXIF 方向数据旋转图像。rotate 方法按给定角度顺时针旋转图像,并接受可选背景色。blur 与 sharpen 方法接受 0 到 100 之间的值。
条件变换
图像实例支持 Laravel 的 Conditionable trait,可用 when 与 unless 方法有条件地应用变换:
$image = $request->image('avatar')
->when($request->boolean('crop'), fn ($image) => $image->cover(400, 400))
->unless($request->boolean('preserve_format'), fn ($image) => $image->toWebp());编码图像
默认情况下,处理后的图像会按原始格式编码。不过,你可在获取或存储前将图像转换为其他受支持的格式:
$image = $image->toWebp();
$image = $image->toJpg();
$image = $image->toJpeg();
$image = $image->toPng();
$image = $image->toGif();
$image = $image->toAvif();
$image = $image->toBmp();可使用 quality 方法设置输出质量。质量会被限制在 1 到 100 之间:
$image = $image->toWebp()->quality(80);optimize 方法是将图像转换为给定格式并设置质量的便捷快捷方式。默认会将图像优化为质量为 70 的 WebP:
$image = $image->optimize();
$image = $image->optimize(format: 'jpg', quality: 85);可将处理后的图像内容获取为字节字符串、Base64 编码字符串或 data URI:
$bytes = $image->toBytes();
$base64 = $image->toBase64();
$dataUri = $image->toDataUri();也可将图像实例转换为字符串以获取 data URI:
$dataUri = (string) $image;存储图像
store 方法将处理后的图像存储到应用的某个文件系统磁盘上。与上传文件一样,Laravel 会生成唯一文件名并返回存储路径。第二个参数可用于指定磁盘:
$path = $request->image('avatar')
->cover(400, 400)
->store(path: 'avatars');
$path = $request->image('avatar')
->cover(400, 400)
->store(path: 'avatars', disk: 's3');可使用 storeAs 方法指定存储的文件名:
$path = $request->image('avatar')
->cover(400, 400)
->storeAs(path: 'avatars', name: 'avatar.jpg', disk: 'public');storePublicly 与 storePubliclyAs 方法会以 public 可见性存储图像:
$path = $request->image('avatar')
->cover(400, 400)
->storePublicly(path: 'avatars', disk: 'public');
$path = $request->image('avatar')
->cover(400, 400)
->storePubliclyAs(path: 'avatars', name: 'avatar.webp', disk: 'public');若图像无法存储,存储方法会返回 false。
检查图像
可使用以下方法获取图像的 MIME 类型、扩展名、尺寸、宽度、高度与主色:
$mimeType = $image->mimeType();
$extension = $image->extension();
[$width, $height] = $image->dimensions();
$width = $image->width();
$height = $image->height();
$dominantColor = $image->dominantColor();这些方法作用于处理后的图像。例如,在 cover(400, 400) 之后调用 width 会返回 400。
图像驱动
自定义图像驱动
Laravel 的图像管理器扩展了 Laravel 的基础 Illuminate\Support\Manager 类。这意味着你可使用图像管理器与 Image Facade 上的 extend 方法注册自定义图像驱动。
自定义图像驱动应实现 Illuminate\Contracts\Image\Driver 接口。process 方法接收原始图像内容以及应应用于图像的有序 Illuminate\Image\ImagePipeline,并应返回处理后的图像字节:
<?php
namespace App\Images;
use Illuminate\Contracts\Image\Driver;
use Illuminate\Image\ImagePipeline;
class VipsDriver implements Driver
{
/**
* Process the given image contents with the specified pipeline.
*/
public function process(string $contents, ImagePipeline $pipeline): string
{
// Apply the pipeline's transformations and output options...
return $contents;
}
/**
* Register a transformation handler.
*/
public function transformUsing(string $transformation, callable $callback): static
{
// Store the handler so it may be applied while processing the pipeline...
return $this;
}
}INFO
要更好地理解如何实现自定义图像驱动,可参阅框架内置的 Illuminate\Image\Drivers\InterventionDriver 类。
实现自定义驱动后,可使用 Image Facade 的 extend 方法注册。通常应在服务提供者的 boot 方法中完成:
use App\Images\VipsDriver;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\Facades\Image;
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Image::extend('vips', function (Application $app) {
return new VipsDriver;
});
}注册驱动后,可使用 using 方法为特定图像指定该驱动:
$image = $request->image('avatar')
->using('vips')
->cover(400, 400);也可通过应用 config/images.php 配置文件中的 default 选项,或 IMAGE_DRIVER 环境变量,将自定义驱动配置为应用的默认图像驱动:
IMAGE_DRIVER=vips自定义变换
应用与包可通过创建实现 Illuminate\Contracts\Image\Transformation 契约的类来定义自定义变换。随后可使用 transform 方法将自定义变换加入图像管道:
<?php
namespace App\Images\Transformations;
use Illuminate\Contracts\Image\Transformation;
class Pixelate implements Transformation
{
public function __construct(
public readonly int $size,
) {
//
}
}接下来,使用 Image Facade 的 transformUsing 方法为该变换与驱动注册处理程序。通常应在服务提供者的 boot 方法中完成:
use App\Images\Transformations\Pixelate;
use Illuminate\Support\Facades\Image;
use Intervention\Image\Interfaces\ImageInterface;
Image::transformUsing('gd', Pixelate::class, function (ImageInterface $image, Pixelate $transformation) {
return $image->pixelate($transformation->size);
});注册变换处理程序后,即可将变换应用于图像:
use App\Images\Transformations\Pixelate;
$image = $request->image('avatar')
->transform(new Pixelate(12))
->store('avatars');