본문으로 건너뛰기
버전: 13.x

Image Manipulation

Introduction

Laravel은 프레임워크 전반에서 사용하는 표현력 있는 규칙과 동일한 방식으로 이미지를 리사이즈하고, 자르고, 인코딩하고, 저장할 수 있는 유연한 이미지 조작 API를 제공합니다. Laravel의 이미지 기능은 Intervention Image를 기반으로 하며 GD 및 Imagick PHP 확장을 지원합니다.

이미지 API는 업로드된 파일, Laravel의 filesystem disks에 저장된 파일, 로컬 파일, 원격 URL 또는 원시 이미지 바이트를 다룰 때 유용합니다:

use Illuminate\Support\Facades\Image;

$path = Image::fromStorage('avatars/photo.jpg', 'public')
->cover(400, 400)
->toWebp()
->quality(80)
->storePublicly('avatars', 'public');

이미지 조작은 CPU와 메모리를 많이 사용할 수 있습니다. 업로드를 수신하는 HTTP 요청 중에 처리하는 대신 대규모 이미지 처리 작업을 queued job에서 수행하는 것을 고려하세요.

Installation

Laravel의 이미지 조작 기능을 사용하기 전에 Composer를 통해 Intervention Image 패키지를 설치합니다:

composer require intervention/image:^4.0

또한 애플리케이션에서 사용할 드라이버에 따라 PHP 설치 환경에 GD 또는 Imagick 확장 기능이 설치되어 있는지 확인해야 합니다.

Configuration

Laravel의 이미지 설정 파일은 config/images.php에 있습니다. 애플리케이션에 images 설정 파일이 없다면 config:publish Artisan 명령어를 사용해 게시할 수 있습니다.

php artisan config:publish images

이미지 설정 파일에서 애플리케이션의 기본 이미지 드라이버를 지정할 수 있습니다. IMAGE_DRIVER 환경 변수를 사용해 기본 드라이버를 지정할 수도 있습니다. 지원되는 드라이버는 gdimagick입니다:

IMAGE_DRIVER=imagick

Reading Images

Image 파사드는 일반적인 소스에서 이미지를 읽는 여러 메서드를 제공합니다. 이미지 콘텐츠는 지연 로드되므로, 일반적으로 이미지를 처리하거나 해당 바이트를 요청할 때까지 소스를 읽지 않습니다.

Uploaded Files

들어오는 요청에서 업로드된 이미지를 가져오려면 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();

Storage Files

애플리케이션의 filesystem disks에 저장된 파일에서 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');

Other Sources

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');

Manipulating Images

이미지 인스턴스는 변경할 수 없습니다. 각 조작 메서드는 변환이 처리 파이프라인에 추가된 새 이미지 인스턴스를 반환하므로 메서드를 유연하게 연결해 사용할 수 있습니다:

$image = $request->image('avatar')
->orient()
->cover(400, 400)
->sharpen(10);

변환은 이미지 파이프라인에 추가된 순서대로 처리되며, 이미지는 마지막에 한 번만 인코딩됩니다.

Resizing Images

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 메서드를 사용해 이미지를 자를 수 있습니다. 처음 두 인수는 원하는 너비와 높이이며, 선택적 세 번째와 네 번째 인수는 자르기 영역의 xy 좌표를 지정합니다.

$image = $image->crop(300, 200);
$image = $image->crop(300, 200, x: 50, y: 25);

Other Transformations

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 메서드는 지정된 각도만큼 이미지를 시계 방향으로 회전하며 선택적 배경 색상을 허용합니다. blursharpen 메서드는 0에서 100 사이의 값을 허용합니다.

Conditional Transformations

이미지 인스턴스는 Laravel의 Conditionable 트레이트를 지원하므로, whenunless 메서드를 사용해 조건부로 변환을 적용할 수 있습니다:

$image = $request->image('avatar')
->when($request->boolean('crop'), fn ($image) => $image->cover(400, 400))
->unless($request->boolean('preserve_format'), fn ($image) => $image->toWebp());

Encoding Images

기본적으로 처리된 이미지는 원래 형식으로 인코딩됩니다. 하지만 이미지를 가져오거나 저장하기 전에 지원되는 다른 형식으로 변환할 수 있습니다.

$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로 인코딩된 문자열 또는 데이터 URI로 가져올 수 있습니다:

$bytes = $image->toBytes();
$base64 = $image->toBase64();
$dataUri = $image->toDataUri();

이미지 인스턴스는 데이터 URI를 가져오기 위해 문자열로 캐스팅할 수도 있습니다:

$dataUri = (string) $image;

Storing Images

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');

storePubliclystorePubliclyAs 메서드는 이미지의 공개 가시성을 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를 반환합니다.

Inspecting Images

다음 메서드를 사용하면 이미지의 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을 반환합니다.

Image Drivers

Custom Image Drivers

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;
}
}

사용자 지정 이미지 드라이버를 구현하는 방법을 더 잘 이해하려면 프레임워크에 내장된 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/images.php 설정 파일에서 default 옵션을 사용하거나 IMAGE_DRIVER 환경 변수를 설정해 커스텀 드라이버를 애플리케이션의 기본 이미지 드라이버로 구성할 수도 있습니다:

IMAGE_DRIVER=vips

Custom Transformations

애플리케이션과 패키지는 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');