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
- Application-wide configuration
- Dependency injection
- Static facade interface
- Image response
- Reading and creating images
- Resizing
- Effects
- Inserting images
- Encoding and saving
- Image information
- Formats
- Differences from PHP
- Not yet ported (planned for a later release)
- License
Installation
Add the crate to your application:
cargo add laravel-image
Register the service provider in src/app.rs:
use ImageServiceProvider;
configure
.with_providers
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 ImageConfig;
configure
.with_config
auto_orientationrotates decoded images according to their Exif orientation.decode_animationkeeps every frame of animated GIFs, or only the first one.background_coloris the default background ofrotate,contain,cropandresize_canvas, and the color JPEG encoding blends transparent areas onto.stripremoves 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 Inject;
use ImageManager;
pub async
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 UploadedFile;
use storage;
use ;
use ;
pub async
| 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 Response;
use storage;
use ;
pub async
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 ;
let image = decode?;
let image = decode?;
let mut canvas = create_image?; // transparent
canvas.fill?;
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 ;
image.resize?; // exact size
image.resize?; // half the width, same height
image.resize_down?; // never upsizes
image.scale?; // keep the aspect ratio
image.scale_down?;
image.cover?; // crop and resize to fill
image.cover_down?;
image.contain?; // fit and pad
image.contain_down?;
image.crop?;
image.resize_canvas?;
image.resize_canvas_relative?;
None for a background uses the configured background_color. Alignments also parse from PHP's strings: "top-left".parse::<Alignment>().
Effects
use Direction;
image.rotate?; // clockwise, as in Intervention Image 4
image.orient; // apply the Exif orientation
image.flip;
image.grayscale.invert;
image.brightness.contrast.gamma;
image.blur.sharpen;
image.pixelate?;
image.colorize?;
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?;
The inserted image may be anything decode accepts. transparency is its opacity from 0.0 to 1.0.
Encoding and saving
use ;
let encoded = image.encode?; // the original format
let jpeg = image.encode_with?;
let progressive = image.encode_with?;
let webp = image.encode_using_format?;
let png = image.encode_using_media_type?;
let gif = image.encode_using_file_extension?;
let avif = image.encode_using_path?;
encoded.as_bytes;
encoded.media_type; // "image/jpeg"
encoded.to_data_uri;
encoded.save?;
image.save?; // format from the extension
image.save_to_origin?; // 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:
disk?.put.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; // Some(Number(6))
image.exif.get; // a whole section
image.color_at; // 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_DRIVERis read intoImageConfig::driverbut 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
ImageConfigsection instead ofconfig/intervention-image.php(or the legacyconfig/image.php), with the same options and defaults. - Facade and macro.
Image::decode(..)and the other facade methods are associated functions ofImage;response()->image(..)isimage.response(..). Named arguments (quality: 65) areEncoderOptions, and optional PHP arguments are explicit (None,Alignment::Center). - Mutation. Modifiers return
&mut Image(orResult<&mut Image>when they can fail); clone an image to keep the original.save()without a path issave_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
qualityis validated but has no effect on WebP. - AVIF encoding needs the
aviffeature; AVIF decoding isn't possible in pure Rust (it needs the dav1d C library). - Ignored encoder options: PNG
interlacedandindexed, GIFinterlacedand TIFFqualityare 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
imagecopyresampledandimagerotate; sizes and positions are the same. - Integer types:
blur,sharpenandpixelatetakeu32andcreate_imagetakesu32, 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(), animatedcreateImage(.., $animation)(AnimationFactory).- Resolution (
resolution(),setResolution()), ICC profiles (profile(),setProfile(),removeProfile()),setColorspace()(CMYK, HSL, ...),colorsAt()and thecolors()extractor. - Custom modifiers and analyzers (
modify(),analyze()),decodeStream(),decodeHttpResponse(). - Color strings other than hex,
rgb()/rgba()andtransparent: named colors,cmyk(),hsl(),hsv(),oklab(),oklch()returnImageError::ColorDecoderfor now.
License
The MIT License (MIT). See LICENSE.md.