Readouble

Laravel 13.x 画像操作

イントロダクションIntroduction

Laravelは、フレームワーク全体で見られる表現力豊かな規約と同じ規約を使用して、画像のサイズ変更、クロップ、エンコード、保存を行える読み書きしやすい画像操作APIを提供しています。Laravelの画像機能はIntervention Imageをベースにしており、GDおよびImagick PHP拡張モジュールをサポートしています。Laravel provides a fluent image manipulation API that allows you to resize, crop, encode, and store images using the same expressive conventions found throughout the framework. Laravel's image features are powered by Intervention Image[https://image.intervention.io/] and support the GD and Imagick PHP extensions.

画像APIは、アップロード済みファイル、Laravelのファイルシステムディスクに保存しているファイル、ローカルファイル、リモートURL、または画像の生バイトを処理するときに便利です。The image API is useful when working with uploaded files, files stored on Laravel filesystem disks[/docs/{{version}}/filesystem], local files, remote URLs, or raw image bytes:

use Illuminate\Support\Facades\Image;

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

warning Warning! 画像操作は、CPUとメモリを大量に消費する可能性があります。大規模な画像処理のワークロードは、アップロードを受け取るHTTPリクエスト中ではなく、ジョブキューで実行することを検討してください。[!WARNING] Image manipulation can be CPU and memory-intensive. Consider performing large image processing workloads on a queued job[/docs/{{version}}/queues] instead of during the HTTP request that receives the upload.

インストールInstallation

Laravelの画像操作機能を使用する前に、Composer経由でIntervention Imageパッケージをインストールしてください。Before using Laravel's image manipulation features, install the Intervention Image package via Composer:

composer require intervention/image:^4.0

また、アプリケーションが使用するドライバに応じて、確実にPHP環境へGDまたはImagick拡張モジュールのいずれかをインストールしてください。You should also ensure your PHP installation has either the GD or Imagick extension installed, depending on which driver your application will use.

設定Configuration

Laravelの画像設定ファイルは、config/image.phpにあります。アプリケーションにimage設定ファイルがない場合は、config:publish Artisanコマンドを使用してリソース公開できます。Laravel's image configuration file is located at config/image.php. If your application does not have an image configuration file, you may publish it using the config:publish Artisan command:

php artisan config:publish image

画像設定ファイルで、アプリケーションのデフォルトの画像ドライバを指定できます。また、IMAGE_DRIVER環境変数を使用してデフォルトのドライバを指定することも可能です。サポートしているドライバは、gdimagickです。The image configuration file allows you to specify your application's default image driver. You may also specify the default driver using the IMAGE_DRIVER environment variable. The supported drivers are gd and imagick:

IMAGE_DRIVER=imagick

画像読み込みReading Images

Imageファサードは、一般的なソースから画像を読み込むためのメソッドをいくつか提供します。画像コンテンツは遅延ロードされるため、通常は画像が処理されるか、そのバイトが要求されるまで、ソースを読み込みません。The Image facade provides several methods for reading images from common sources. Image contents are loaded lazily, so the source is typically not read until the image is processed or its bytes are requested.

アップロード済みファイルUploaded Files

imageメソッドを使用すれば、受信リクエストからアップロードした画像を取得できます。このメソッドは、アップロードしたファイルのIlluminate\Image\Imageインスタンスを返します。ファイルが存在しない場合はnullを返します。You may retrieve an uploaded image from an incoming request using the image method. This method returns an Illuminate\Image\Image instance for the uploaded file, or null if the file is not present:

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インスタンスから画像インスタンスを作成することもできます。Alternatively, you may create an image instance from an Illuminate\Http\UploadedFile instance using the fromUpload method:

use Illuminate\Support\Facades\Image;

$image = Image::fromUpload($request->file('avatar'));

アップロード済みファイルから画像を作成した場合、fileメソッドを使用して基になるアップロードファイルを取得できます。When an image is created from an uploaded file, you may retrieve the underlying uploaded file using the file method:

$file =$image->file();

保存ファイルStorage Files

fromStorageメソッドを使用すれば、アプリケーションのファイルシステムディスクのいずれかに保存しているファイルから画像インスタンスを作成できます。第1引数はファイルへのパス、第2引数はディスク名です。You may create an image instance from a file stored on one of your application's filesystem disks[/docs/{{version}}/filesystem] using the fromStorage method. The first argument is the path to the file, while the second argument is the disk name:

use Illuminate\Support\Facades\Image;

$image = Image::fromStorage('avatars/photo.jpg', disk: 'public');

また、imageメソッドを使用して、ファイルシステムディスクインスタンスから直接画像インスタンスを作成することもできます。You may also create image instances directly from a filesystem disk instance using the image method:

use Illuminate\Support\Facades\Storage;

$image = Storage::disk('public')->image('avatars/photo.jpg');

その他のソースOther Sources

Imageファサードには、生のバイト、ローカルファイルのパス、リモートURL、およびBase64エンコードされた文字列から画像インスタンスを作成するためのメソッドも用意しています。The Image facade also includes methods for creating image instances from raw bytes, local file paths, remote URLs, and Base64 encoded strings:

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](https://example.com/photo.jpg)');

画像操作Manipulating Images

画像インスタンスはイミュータブルです。各操作メソッドは、処理パイプラインに変換を追加した新しい画像インスタンスを返すため、メソッドを流暢にチェーンできます。Image instances are immutable. Each manipulation method returns a new image instance with the transformation appended to its processing pipeline, allowing methods to be chained fluently:

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

変換は、画像パイプラインに追加した順に処理され、画像は最後に1回だけエンコードされます。Transformations are processed in the order they are added to the image pipeline and the image is only encoded once at the end.

画像リサイズResizing Images

resizeメソッドは、画像を特定のサイズに変更します。幅と高さの両方を指定することも、名前付き引数を使用して1つの次元だけを指定することもできます。The resize method resizes an image to the given dimensions. You may provide both a width and height, or provide only one dimension using named arguments:

$image =$image->resize(800, 600);
$image =$image->resize(width: 800);
$image =$image->resize(height: 600);

scaleメソッドは、指定したサイズに収まるように画像を比例的に縮小します。このメソッドが画像のサイズを拡大することはありません。The scale method proportionally scales an image down so that it fits within the given dimensions. This method will never increase the size of an image:

$image =$image->scale(800, 600);
$image =$image->scale(width: 800);
$image =$image->scale(height: 600);

coverメソッドは、指定したサイズを完全に覆うように画像のサイズを変更し、クロップします。The cover method resizes and crops an image to completely cover the given dimensions:

$image =$image->cover(400, 400);

containメソッドは、画像全体を維持しながら、指定したサイズに収まるように画像のサイズを変更します。必要に応じて、オプションの背景色を使用して空白を埋めます。The contain method resizes an image to fit within the given dimensions while preserving the entire image. If necessary, empty space will be filled using the optional background color:

$image =$image->contain(400, 400);
$image =$image->contain(400, 400, '#ffffff');

cropメソッドを使用して画像をクロップできます。最初の2つの引数は希望する幅と高さで、オプションの第3引数と第4引数でクロップのx座標とy座標を指定します。You may crop an image using the crop method. The first two arguments are the desired width and height, and the optional third and fourth arguments specify the crop's x and y coordinates:

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

他の操作Other Transformations

Laravelは、他にもさまざまな画像変換メソッドを提供しています。Laravel also provides a variety of additional image transformation methods:

$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の間の値を受け入れます。The orient method rotates the image according to its EXIF orientation data. The rotate method rotates the image clockwise by the given angle and accepts an optional background color. The blur and sharpen methods accept values between 0 and 100.

条件付き操作Conditional Transformations

画像インスタンスはLaravelのConditionableトレイトをサポートしているため、whenメソッドとunlessメソッドを使用して、条件付きで変換を適用できます。Image instances support Laravel's Conditionable trait, allowing you to conditionally apply transformations using the when and unless methods:

$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

デフォルトでは、処理済みの画像は元のフォーマットを使用してエンコードされます。ただし、画像を取得または保存する前に、別のサポートしているフォーマットに変換できます。By default, processed images are encoded using their original format. However, you may convert the image to another supported format before retrieving or storing it:

$image =$image->toWebp();
$image =$image->toJpg();
$image =$image->toJpeg();

qualityメソッドを使用して、出力品質を設定できます。品質は1から100の間に制限されます。You may use the quality method to set the output quality. The quality will be clamped between 1 and 100:

$image =$image->toWebp()->quality(80);

optimizeメソッドは、画像を指定したフォーマットに変換し、その品質を設定するための便利なショートカットです。デフォルトでは、画像は品質70のWebP画像として最適化されます。The optimize method is a convenient shortcut for converting the image to a given format and setting its quality. By default, images are optimized as WebP images with a quality of 70:

$image =$image->optimize();

$image =$image->optimize(format: 'jpg', quality: 85);

処理済みの画像コンテンツをバイト文字列、base64エンコードされた文字列、またはデータURIとして取得できます。You may retrieve the processed image contents as a string of bytes, base64 encoded string, or data URI:

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

画像インスタンスを文字列にキャストして、処理済みのバイトを取得することもできます。An image instance may also be cast to a string to retrieve its processed bytes:

$bytes = (string)$image;

画像の保存Storing Images

storeメソッドは、処理済みの画像をアプリケーションのファイルシステムディスクのいずれかに保存します。アップロードしたファイルと同様に、Laravelはユニークなファイル名を生成し、保存したパスを返します。第2引数を使用してディスクを指定できます。The store method stores the processed image on one of your application's filesystem disks. Like uploaded files, Laravel will generate a unique filename and return the stored path. The second argument may be used to specify the disk:

$path =$request->image('avatar')
    ->cover(400, 400)
    ->store(path: 'avatars');

$path =$request->image('avatar')
    ->cover(400, 400)
    ->store(path: 'avatars', disk: 's3');

storeAsメソッドを使用して、保存するファイル名を指定できます。You may use the storeAs method to specify the stored filename:

$path =$request->image('avatar')
    ->cover(400, 400)
    ->storeAs(path: 'avatars', name: 'avatar.jpg', disk: 'public');

storePubliclyメソッドとstorePubliclyAsメソッドは、画像をpublicな公開設定で保存します。The storePublicly and storePubliclyAs methods store the image with public visibility:

$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を返します。If the image could not be stored, the storage methods return false.

画像の調査Inspecting Images

以下のメソッドを使用して、画像のMIMEタイプ、拡張子、サイズ、幅、および高さを取得できます。You may retrieve the image's MIME type, extension, dimensions, width, and height using the following methods:

$mimeType =$image->mimeType();
$extension =$image->extension();

[$width, $height] =$image->dimensions();
$width =$image->width();
$height =$image->height();

これらのメソッドは、処理済みの画像に対して動作します。たとえば、cover(400, 400)の後にwidthを呼び出すと、400を返します。These methods operate on the processed image. For example, calling width after cover(400, 400) will return 400.

画像ドライバImage Drivers

画像ドライバのカスタマイズCustom Image Drivers

Laravelの画像マネージャは、LaravelのベースであるIlluminate\Support\Managerクラスを拡張しています。つまり、画像マネージャおよびImageファサードで利用できるextendメソッドを使用して、カスタム画像ドライバを登録できます。Laravel's image manager extends Laravel's base Illuminate\Support\Manager class. This means you may register custom image drivers using the extend method available on the image manager and Image facade.

カスタム画像ドライバは、Illuminate\Contracts\Image\Driverインターフェイスを実装する必要があります。processメソッドは、元の画像コンテンツと、画像に適用すべき順序付けられたIlluminate\Image\ImagePipelineを受け取り、処理済みの画像バイトを返す必要があります。Custom image drivers should implement the Illuminate\Contracts\Image\Driver interface. The process method receives the original image contents and the ordered Illuminate\Image\ImagePipeline that should be applied to the image, and should return the processed image bytes:

<?php

namespace App\Images;

use Illuminate\Contracts\Image\Driver;
use Illuminate\Image\ImagePipeline;

class VipsDriver implements Driver
{
    /**
     * 指定パイプラインで、特定の画像コンテンツを処理
     */
    public function process(string $contents, ImagePipeline$pipeline): string
    {
        // パイプラインの変換と出力オプションを適用…

        return $contents;
    }

    /**
     * 変換ハンドラの登録
     */
    public function transformUsing(string $transformation, callable$callback): static
    {
        // パイプラインの処理中に適用できるように、ハンドラを保存…

        return $this;
    }
}

note Note: カスタム画像ドライバの実装方法をより深く理解するために、フレームワークに組み込まれているIlluminate\Image\Drivers\InterventionDriverクラスを確認するとよいでしょう。[!NOTE] To better understand how to implement a custom image driver, you may review the framework's built-in Illuminate\Image\Drivers\InterventionDriver class.

カスタムドライバを実装したら、Imageファサードのextendメソッドを使用して登録できます。通常、これはサービスプロバイダのbootメソッドで行います。Once you have implemented your custom driver, you may register it using the Image facade's extend method. Typically, this should be done in the boot method of a service provider:

use App\Images\VipsDriver;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\Facades\Image;

/**
 * 全アプリケーションサービスの初期起動処理
 */
public function boot(): void
{
    Image::extend('vips', function (Application $app) {
        return new VipsDriver;
    });
}

ドライバを登録した後は、usingメソッドを使用して、指定画像へそのドライバを使用できます。After registering the driver, you may use it for a specific image using the using method:

$image =$request->image('avatar')
    ->using('vips')
    ->cover(400, 400);

また、アプリケーションのconfig/image.php設定ファイルのdefaultオプション、またはIMAGE_DRIVER環境変数を使用して、カスタムドライバをアプリケーションのデフォルトの画像ドライバとして設定することもできます。You may also configure a custom driver as your application's default image driver using the default option in your application's config/image.php configuration file or the IMAGE_DRIVER environment variable:

IMAGE_DRIVER=vips

カスタム操作Custom Transformations

アプリケーションやパッケージは、Illuminate\Contracts\Image\Transformation契約を実装するクラスを作成することで、カスタム変換を定義できます。その後、transformメソッドを使用して、カスタム変換を画像パイプラインに追加できます。Applications and packages may define custom transformations by creating a class that implements the Illuminate\Contracts\Image\Transformation contract. Custom transformations can then be added to an image pipeline using the transform method:

<?php

namespace App\Images\Transformations;

use Illuminate\Contracts\Image\Transformation;

class Pixelate implements Transformation
{
    public function __construct(
        public readonly int $size,
    ) {
        //
    }
}

次に、ImageファサードのtransformUsingメソッドを使用して、変換とドライバのハンドラを登録します。通常、これはサービスプロバイダのbootメソッドで行います。Next, register a handler for the transformation and driver using the Image facade's transformUsing method. Typically, this should be done in the boot method of a service provider:

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

変換ハンドラを登録すると、画像へその変換を適用できます。Once the transformation handler has been registered, you may apply the transformation to an image:

use App\Images\Transformations\Pixelate;

$image =$request->image('avatar')
    ->transform(new Pixelate(12))
    ->store('avatars');

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

テストコード表示
両コード表示
Pestのみ表示
PHPUnitのみ表示
OS表示
全OS表示
macOSのみ表示
windowsのみ表示
linuxのみ表示
JSフレームワーク
両フレームワーク
Reactのみ表示
Vueのみ表示
Svelteのみ表示
JSのみ表示

(JSが存在しない場合は、他を全表示)

和文変換

対象文字列と置換文字列を半角スペースで区切ってください。(最大5組各10文字まで)

本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作