图像处理
介绍
Laravel 提供了流畅的图像处理 API,允许您使用整个框架中一致的表达方式来调整大小、裁剪、编码和存储图像。Laravel 的图像功能由 Intervention Image 驱动,并支持 GD 和 Imagick PHP 扩展。
图像 API 在处理上传的文件、存储在 Laravel 文件系统磁盘 上的文件、本地文件、远程 URL 或原始图像字节时非常有用:
use Illuminate\Support\Facades\Image;
$path = Image::fromStorage('avatars/photo.jpg', 'public')
->cover(400, 400)
->toWebp()
->quality(80)
->storePublicly('avatars', 'public');警告
图像处理可能会大量消耗 CPU 和内存。请考虑在 队列作业 上执行大型图像处理工作负载,而不是在接收上传的 HTTP 请求期间处理。
安装
在使用 Laravel 的图像处理功能之前,请通过 Composer 安装 Intervention Image 包:
composer require intervention/image:^4.0您还应确保您的 PHP 安装包含 GD 或 Imagick 扩展,具体取决于您的应用程序将使用的驱动。
配置
Laravel 的图像配置文件位于 config/image.php。如果您的应用程序没有 image 配置文件,您可以使用 config:publish Artisan 命令发布它:
php artisan config:publish image图像配置文件允许您指定应用程序的默认图像驱动。您也可以使用 IMAGE_DRIVER 环境变量指定默认驱动。支持的驱动有 gd 和 imagick:
IMAGE_DRIVER=imagick读取图像
Image 门面提供了多种从常见来源读取图像的方法。图像内容是延迟加载的,因此通常只有在处理图像或请求其字节时才会读取源。
上传的文件
您可以使用 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 门面还包含从原始字节、本地文件路径、远程 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');您可以使用 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->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();您可以使用 quality 方法设置输出质量。质量值将被限制在 1 到 100 之间:
$image = $image->toWebp()->quality(80);optimize 方法是一个便捷的快捷方式,用于将图像转换为指定格式并设置其质量。默认情况下,图像将被优化为质量 70 的 WebP 图像:
$image = $image->optimize();
$image = $image->optimize(format: 'jpg', quality: 85);您可以将处理后的图像内容作为字节字符串、base64 编码字符串或数据 URI 来获取:
$bytes = $image->toBytes();
$base64 = $image->toBase64();
$dataUri = $image->toDataUri();图像实例也可以被转换为字符串以获取其处理后的字节:
$bytes = (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();这些方法操作的是处理后的图像。例如,在 cover(400, 400) 之后调用 width 将返回 400。
图像驱动
自定义图像驱动
Laravel 的图像管理器扩展了 Laravel 基础的 Illuminate\Support\Manager 类。这意味着您可以使用图像管理器和 Image 门面上提供的 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;
}
}NOTE
为了更好地理解如何实现自定义图像驱动,您可以查看框架内置的 Illuminate\Image\Drivers\InterventionDriver 类。
一旦实现了自定义驱动,您就可以使用 Image 门面的 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/image.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 门面的 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');