laravel-image 0.2.0

Image handling and manipulation for Laravel Rust, in pure Rust: a port of intervention/image-laravel and Intervention Image.
Documentation

Image for Laravel Rust

laravel-image reads, modifies, encodes and serves images in Laravel Rust applications. It is a port of intervention/image-laravel (the Laravel integration: configuration, Image facade, image response) together with the core of Intervention Image, running on a pure-Rust driver: no GD, no Imagick, no C libraries.

[!NOTE] This is a community package maintained by Rivervo. It is not an official package of Intervention or Oliver Vogel. It follows intervention/image-laravel 4.1.1 and Intervention Image 4.4.2: the same method names (in Rust naming), the same configuration options and defaults, and the arithmetic of Intervention's GD driver. All credit for the API goes to its author.

Installation

Add the crate to your application:

cargo add laravel-image

Register the service provider in src/app.rs:

use laravel_image::ImageServiceProvider;

Application::configure()
    .with_providers(|providers| {
        providers.add(ImageServiceProvider);
    })

There's nothing to migrate and nothing to install on the server. AVIF encoding is optional because its encoder (rav1e) takes long to compile:

cargo add laravel-image --features avif

The crates doing the work are image (decoding and encoding), fast_image_resize (resampling), jpeg-encoder (JPEG with progressive mode), kamadak-exif (Exif) and gif (animation loops), all pure Rust.

Application-wide configuration

The provider adds the ImageConfig section with the defaults of config/intervention-image.php:

PHP option ImageConfig field Default Environment
driver driver gd IMAGE_DRIVER
options.autoOrientation auto_orientation true
options.decodeAnimation decode_animation true
options.backgroundColor background_color ffffff
options.strip strip false

Change them in src/app.rs:

use laravel_image::ImageConfig;

Application::configure()
    .with_config(|config, _| {
        let image = config.section_mut::<ImageConfig>();
        image.decode_animation = false;
        image.background_color = "000000".to_owned();
    })
  • auto_orientation rotates decoded images according to their Exif orientation.
  • decode_animation keeps every frame of animated GIFs, or only the first one.
  • background_color is the default background of rotate, contain, crop and resize_canvas, and the color JPEG encoding blends transparent areas onto.
  • strip removes metadata when encoding. The pure-Rust driver, like PHP's GD driver, never writes metadata, so encoded images are always stripped.

There is a single driver, so driver (IMAGE_DRIVER) is read but every value selects the pure-Rust driver; see Differences from PHP.

Dependency injection

The provider binds an ImageManager built from the configuration, PHP's ImageManagerInterface:

use laravel::container::Inject;
use laravel_image::ImageManager;

pub async fn upload(images: Inject<ImageManager>, Valid(form): Valid<UploadImage>) -> laravel::Result<Redirect> {
    let image = images.decode_uploaded_file(&form.image)?;
    // ...
}

ImageManager::new(DriverConfig { .. }) makes a manager with options of your own, and ImageManager::using_driver() one with the defaults.

Static facade interface

The Image facade's functions are associated functions of Image, using the configured manager:

use laravel::http::UploadedFile;
use laravel::storage;
use laravel::validation::{Valid, Validate};
use laravel_image::{EncoderOptions, Image};

#[derive(serde::Deserialize, Validate)]
#[validate(anyone)]
pub struct UploadImage {
    #[validate(required)]
    image: UploadedFile,
}

pub async fn store(Valid(form): Valid<UploadImage>) -> laravel::Result<Redirect> {
    let mut image = Image::decode(&form.image)?;
    image.resize(300, 200)?;

    let extension = form.image.extension().unwrap_or("jpg");
    storage::put(
        &format!("photos/1.{extension}"),
        image.encode_using_file_extension(extension, EncoderOptions::new().quality(70))?,
    )
    .await?;

    Ok(Redirect::back())
}
PHP Rust
Image::decode($source) Image::decode(source)
Image::decodePath($path) Image::decode_path(path)
Image::decodeBinary($binary) Image::decode_binary(bytes)
Image::decodeBase64($base64) Image::decode_base64(text)
Image::decodeDataUri($dataUri) Image::decode_data_uri(text)
Image::decodeSplFileInfo($file) Image::decode_uploaded_file(&upload)
Image::createImage($width, $height) Image::create_image(width, height)

decode takes a string (tried as a data URI, then Base64, then a path, as in PHP), a Path, bytes (Vec<u8>, &[u8], the Bytes that storage::get returns), an UploadedFile, an EncodedImage or another Image.

Image response

response()->image($image, $format, ...$options) is image.response(format, options), or ImageResponseFactory::make(&image, format, options). It encodes the image and returns a 200 response with the format's Content-Type:

use laravel::http::Response;
use laravel::storage;
use laravel_image::{EncoderOptions, Format, Image};

pub async fn show() -> laravel::Result<Response> {
    let mut image = Image::decode(storage::get("example.jpg").await?)?;
    image.scale(300, 200)?;

    Ok(image.response(Format::Webp, EncoderOptions::new().quality(65))?)
}

The format may be a Format, a MediaType, a FileExtension, a string ("gif", "image/jpeg"), or None for the format the image was decoded from (JPEG for created images). An unknown string is an ImageError::InvalidArgument.

Reading and creating images

use laravel_image::{Image, ImageManager};

let image = Image::decode("storage/app/photo.jpg")?;
let image = Image::decode(bytes)?;
let mut canvas = Image::create_image(640, 480)?; // transparent
canvas.fill("f50", None, None)?;

Errors are ImageError values named after PHP's exceptions: DirectoryNotFound, FileNotFound, Decoder, NotSupported, InvalidArgument, ... They convert into laravel::Error with ?.

Resizing

Modifiers change the image in place and return it, so they chain. Sizes take pixels, a Fraction (Fraction::Half) or None where PHP takes null:

use laravel_image::{Alignment, Fraction};

image.resize(300, 200)?;                 // exact size
image.resize(Fraction::Half, None)?;     // half the width, same height
image.resize_down(300, 200)?;            // never upsizes
image.scale(300, None)?;                 // keep the aspect ratio
image.scale_down(300, 200)?;
image.cover(300, 300, Alignment::Center)?;           // crop and resize to fill
image.cover_down(300, 300, Alignment::Center)?;
image.contain(300, 300, Some("ccc"), Alignment::Center)?; // fit and pad
image.contain_down(300, 300, None, Alignment::Center)?;
image.crop(100, 100, 25, 25, None, Alignment::TopLeft)?;
image.resize_canvas(400, 400, Some("ff0"), Alignment::Center)?;
image.resize_canvas_relative(20, 20, None, Alignment::Center)?;

None for a background uses the configured background_color. Alignments also parse from PHP's strings: "top-left".parse::<Alignment>().

Effects

use laravel_image::Direction;

image.rotate(45.0, Some("fff"))?; // clockwise, as in Intervention Image 4
image.orient();                   // apply the Exif orientation
image.flip(Direction::Horizontal);
image.grayscale().invert();
image.brightness(30).contrast(20).gamma(1.6);
image.blur(5).sharpen(10);
image.pixelate(12)?;
image.colorize(30, 0, -10)?;

Brightness, contrast, gamma, colorize, grayscale, invert, blur and sharpen use the formulas of PHP's GD filters, so results match the GD driver.

Inserting images

insert($image, $x, $y, $alignment, $transparency) draws a watermark on every frame:

image.insert("storage/app/logo.png", 10, 10, Alignment::BottomRight, 0.5)?;

The inserted image may be anything decode accepts. transparency is its opacity from 0.0 to 1.0.

Encoding and saving

use laravel_image::{EncoderOptions, Format, JpegEncoder, MediaType};

let encoded = image.encode()?;                                   // the original format
let jpeg = image.encode_with(JpegEncoder::new(65))?;
let progressive = image.encode_with(JpegEncoder { progressive: true, ..JpegEncoder::default() })?;
let webp = image.encode_using_format(Format::Webp, EncoderOptions::new())?;
let png = image.encode_using_media_type("image/png", EncoderOptions::new())?;
let gif = image.encode_using_file_extension("gif", EncoderOptions::new())?;
let avif = image.encode_using_path("photo.avif", EncoderOptions::new().quality(60))?;

encoded.as_bytes();
encoded.media_type();   // "image/jpeg"
encoded.to_data_uri();
encoded.save("storage/app/photo.jpg")?;

image.save("storage/app/thumb.webp", EncoderOptions::new())?; // format from the extension
image.save_to_origin(EncoderOptions::new())?;                // PHP's save() without a path

EncoderOptions holds PHP's named encoder options (quality, progressive, interlaced, indexed, strip); each encoder takes the ones it knows. The encoders are JpegEncoder, PngEncoder, GifEncoder, WebpEncoder, AvifEncoder, BmpEncoder, TiffEncoder and IcoEncoder, plus HeicEncoder, Jpeg2000Encoder and JxlEncoder, which return ImageError::NotSupported as they do with GD.

An EncodedImage is valid storage contents, so it goes straight to a disk:

storage::disk("s3")?.put("thumbs/1.webp", image.encode_using_format(Format::Webp, EncoderOptions::new())?).await?;

Image information

image.width();
image.height();
image.size();                       // Size, with aspect_ratio(), is_landscape(), ...
image.colorspace();                 // Colorspace::Rgb
image.origin().media_type();        // "image/jpeg"
image.origin().file_path();
image.exif().get("IFD0.Orientation"); // Some(Number(6))
image.exif().get("EXIF");           // a whole section
image.color_at(10, 10, 0);          // Some(Color)
image.is_animated();
image.count();                      // frames
image.loops();

Formats

Format Decode Encode
JPEG yes yes, quality and progressive
PNG yes yes
GIF yes, animated yes, animated
WebP yes yes, lossless only
AVIF no with the avif feature
BMP, TIFF, ICO yes yes
HEIC, JPEG 2000, JPEG XL no no

Differences from PHP

  • One driver. PHP chooses GD, Imagick or Vips; this port has one pure-Rust driver that follows the GD driver's behavior. IMAGE_DRIVER is read into ImageConfig::driver but doesn't change anything. Images are processed as 8-bit RGBA like GD, so 16-bit PNGs are reduced to 8 bits.
  • Configuration is the ImageConfig section instead of config/intervention-image.php (or the legacy config/image.php), with the same options and defaults.
  • Facade and macro. Image::decode(..) and the other facade methods are associated functions of Image; response()->image(..) is image.response(..). Named arguments (quality: 65) are EncoderOptions, and optional PHP arguments are explicit (None, Alignment::Center).
  • Mutation. Modifiers return &mut Image (or Result<&mut Image> when they can fail); clone an image to keep the original. save() without a path is save_to_origin().
  • Exif is read with image.exif().get("IFD0.Orientation") instead of $image->exif('IFD0.Orientation'); integer tags are numbers and text tags strings.
  • WebP is encoded lossless. No maintained pure-Rust lossy WebP encoder exists, so quality is validated but has no effect on WebP.
  • AVIF encoding needs the avif feature; AVIF decoding isn't possible in pure Rust (it needs the dav1d C library).
  • Ignored encoder options: PNG interlaced and indexed, GIF interlaced and TIFF quality are accepted but the encoders don't support them, so output is non-interlaced truecolor PNG, non-interlaced GIF and lossless TIFF.
  • Resampling and free rotation use bilinear filtering (fast_image_resize and a bilinear rotation), so edge pixels can differ slightly from GD's imagecopyresampled and imagerotate; sizes and positions are the same.
  • Integer types: blur, sharpen and pixelate take u32 and create_image takes u32, so negative values can't be passed (PHP throws for them).

Not yet ported (planned for a later release)

  • text() and fonts.
  • Drawing: drawPixel, drawRectangle, drawEllipse, drawCircle, drawPolygon, drawLine, drawBezier, draw().
  • trim(), reduceColors(), fillTransparentAreas(), sliceAnimation(), animated createImage(.., $animation) (AnimationFactory).
  • Resolution (resolution(), setResolution()), ICC profiles (profile(), setProfile(), removeProfile()), setColorspace() (CMYK, HSL, ...), colorsAt() and the colors() extractor.
  • Custom modifiers and analyzers (modify(), analyze()), decodeStream(), decodeHttpResponse().
  • Color strings other than hex, rgb()/rgba() and transparent: named colors, cmyk(), hsl(), hsv(), oklab(), oklch() return ImageError::ColorDecoder for now.

License

The MIT License (MIT). See LICENSE.md.