Intervention Image Laravel Integration

repository·develop·Indexed 41 days ago

https://github.com/intervention/image-laravel

A Laravel integration for the Intervention Image library providing a service provider, facade, and configuration management. It enables seamless image processing within Laravel (>= 8) via dependency injection of the ImageManager, a dedicated Image facade, and a response()->image() macro for returning processed images as HTTP responses.

Tokens
2.7K
Snippets
12
Records
13
Agent score
49%

What's inside Intervention Image Laravel

  1. Configure Intervention Image globally

    develop

    To manage image processing settings centrally, publish the configuration file to config/intervention-image.php using the Artisan command. This allows you to set the driver and global behavior options once for the entire application.

    php artisan vendor:publish --provider="Intervention\Image\Laravel\ServiceProvider"
  2. Reference the Intervention Image configuration

    develop

    The config/intervention-image.php file contains the following keys:

    • driver: The class name of the driver to use. Supported options:
      • \Intervention\Image\Drivers\Gd\Driver::class (Default)
      • \Intervention\Image\Drivers\Imagick\Driver::class
      • \Intervention\Image\Drivers\Vips\Driver::class
    • options: An array of behavior settings:
      • autoOrientation: (bool) Whether to automatically rotate images based on Exif data.
      • decodeAnimation: (bool) Whether to decode animated images.
      • backgroundColor: (string) The default background & blending color (e.g., 'ffffff').
      • strip: (bool) Whether to remove metadata like Exif tags when encoding.
    return [
        'driver' => env('IMAGE_DRIVER', \Intervention\Image\Drivers\Gd\Driver::class),
        'options' => [
            'autoOrientation' => true,
            'decodeAnimation' => true,
            'backgroundColor' => 'ffffff',
            'strip' => false,
        ]
    ];
  3. Publish the Intervention Image configuration

    develop

    To customize the image driver and global options (like autoOrientation, decodeAnimation, backgroundColor, and strip), you can publish the package's configuration file to your application's config directory using the following Artisan command.

    php artisan vendor:publish --provider="Intervention\Image\Laravel\ServiceProvider"
  4. Return an image as an HTTP response using the response macro

    develop

    The package adds a response()->image() macro to Laravel's response factory. This allows you to encode an image resource and return it as an HTTP response in a single step. The first parameter is the image instance, followed by the format and optional quality.

    use Illuminate\Support\Facades\Route;
    use Illuminate\Support\Facades\Storage;
    use Intervention\Image\Format;
    use Intervention\Image\Laravel\Facades\Image;
    
    Route::get('/', function () {
        $image = Image::decode(Storage::get('example.jpg'));
        $image = $image->scale(300, 200);
    
        return response()->image($image, Format::WEBP, quality: 65);
    });
  5. Use the Intervention Image Facade

    develop

    Access the centrally configured image manager singleton using the Intervention\Image\Laravel\Facades\Image facade. This is useful for quick image manipulation within routes or other parts of the application.

    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Route;
    use Illuminate\Support\Facades\Storage;
    use Illuminate\Support\Str;
    use Intervention\Image\Laravel\Facades\Image;
    
    Route::get('/', function (Request $request) {
        $upload = $request->file('image');
        $image = Image::decode($upload);
        $image = $image->resize(300, 200);
    
        Storage::put(
            Str::random() . '.' . $upload->getClientOriginalExtension(),
            $image->encodeUsingFileExtension($upload->getClientOriginalExtension(), quality: 70)
        );
    });
  6. Inject the Image Manager via Dependency Injection

    develop

    You can resolve a manager instance configured with your application-wide settings by injecting Intervention\Image\Interfaces\ImageManagerInterface or Intervention\Image\ImageManager into your classes.

    use Intervention\Image\Interfaces\ImageManagerInterface;
    use Illuminate\Http\Request;
    
    class ImageController extends Controller
    {
        public function __construct(
            protected ImageManagerInterface $imageManager,
        ) {}
    
        public function handleImageUpload(Request $request): RedirectResponse
        {
            $image = $this->imageManager->decodeSplFileInfo($request->file('image'));
        }
    }
  7. Configure Intervention Image options

    develop

    The package uses a configuration file to set up the ImageManager. The available configuration keys are:

    • driver: The image driver to use (e.g., gd or imagick).
    • options.autoOrientation: Boolean. Whether to automatically orient the image based on EXIF data. Defaults to true.
    • options.decodeAnimation: Boolean. Whether to decode animated images. Defaults to true.
    • options.backgroundColor: The background color to use for transparent images (e.g., 'ffffff').
    • options.strip: Boolean. Whether to strip metadata from the image. Defaults to false.

    Note: The package supports both the new intervention-image.php config name and a legacy image.php config name.

  8. Inject the ImageManager via Dependency Injection

    develop

    The package binds the ImageManager and its interface to the Laravel Service Container. You can type-hint either Intervention\Image\ImageManager or Intervention\Image\Interfaces\ImageManagerInterface in your controllers or services to access the image processing capabilities.

    use Intervention\Image\Interfaces\ImageManagerInterface;
    
    public function __construct(ImageManagerInterface $manager)
    {
        $this->manager = $manager;
    }
  9. Use the `image` Response macro

    develop

    The package registers an image macro on Laravel's Response facade. This allows you to return an ImageInterface instance directly as an HTTP response. The macro handles the conversion of the image to a response with the appropriate format and options.

    use Intervention//... (other imports)
    
    return response()->image($image, 'webp');
  10. Use the Image Facade to manage images

    develop

    The Intervention\Image\Laravel\Facades\Image facade provides a static interface to the Intervention Image manager within your Laravel application. It allows you to create new images or decode existing image data from various sources into an ImageInterface instance.

    Common tasks include:

    • Creating a blank image with specific dimensions.
    • Decoding images from file paths, binary data, Base64 strings, or Data URIs.
    use Intervention\Image\Laravel\Facades\Image;
    
    // Create a new blank image
    $image = Image::createImage(800, 600);
    
    // Decode an image from a file path
    $image = Image::decodePath($path);
    
    // Decode an image from a Base64 string
    $image = Image::decodeBase64($base64String);
  11. Create an HTTP image response with ImageResponseFactory::make()

    develop

    The ImageResponseFactory::make() static method allows you to quickly convert an ImageInterface instance into a Laravel Illuminate\/Http\/Response object. This is useful for returning processed images directly from a controller.

    You can specify the target format using a string (e.g., 'webp'), a Format object, a MediaType object, or a FileExtension object. If no format is provided, the factory attempts to use the original image's media type, falling back to JPEG if it cannot be determined.

    You can also pass additional options to the encoder via variadic arguments.

    use Intervention\Image\Laravel\ImageResponseFactory;
    
    // Returns a Laravel Response object with the image content and correct Content-Type header
    return ImageResponseFactory::make($image, 'webp', $encodingOptions);