Rust

Image

Partly Rust
Image previews: decode, crop by gravity or focal point, borders, rounded corners, opacity, rotation and background, then encode to JPEG, PNG, GIF, WebP or AVIF.

In Appwrite#

Appwrite runs some of its classes from the Rust crate; the rest are still PHP.

2 PHP classes served from Rust13 still PHP
Rust 3,257 lines (2,290 code)· PHP 329 lines (195 code)split
PartCodeCommentsBlankTotalFiles
Rust source2,2907352323,25714
PHP source195845032913

Comments include doc comments. Each side counts its src/; the PHP side is what the package still has in PHP.

Served from Rust (2)
Utopia\Image\CanvasUtopia\Image\Font
Still PHP (13)
Utopia\Image\BlankUtopia\Image\BorderUtopia\Image\Exception\CorruptImageExceptionUtopia\Image\Exception\ImageExceptionUtopia\Image\Exception\LimitExceededExceptionUtopia\Image\Exception\UnsupportedFormatExceptionUtopia\Image\FormatUtopia\Image\GravityUtopia\Image\LimitsUtopia\Image\PathUtopia\Image\PointUtopia\Image\TextUtopia\Image\Transform

Install#

Shell
cargo add utopia-image

Getting started#

Common tasks with Image, each a complete program you can copy and run.

utopia-image turns an uploaded image into a preview: decode it, crop it, decorate it, and encode it in the format the client asked for. Everything runs in memory on the calling thread; in async code, run it on the blocking pool.

Make a thumbnail

Decode the blob, crop it to the target size (the centre is kept, scaled to cover), and encode it.

Rust
use utopia_image::{Gravity, Image, OutputFormat};

let blob = std::fs::read("../../../packages/image/tests/resources/disk-a/kitten-1.jpg")?;
let mut image = Image::new(&blob)?;
image.crop(400, 400, Gravity::Center, None)?;
let preview = image.output(OutputFormat::Jpeg, 80)?;
assert_eq!(&preview[..2], &[0xFF, 0xD8]);
PHP
use Utopia\Image\Image;

$image = new Image(file_get_contents('/usr/src/code/packages/image/tests/resources/disk-a/kitten-1.jpg'));
$image->crop(400, 400);
$preview = $image->output('jpg', 80);
echo bin2hex(substr($preview, 0, 2)), "\n"; // ffd8

Keep a point of interest in view

A gravity keeps an edge or a corner; a focal point (fractions of the width and height) keeps a spot as centred as the edges allow. A request that carries the coordinates separately can check them with FocalPoint::from_parts.

Rust
use utopia_image::{FocalPoint, Gravity, Image, OutputFormat};

let blob = std::fs::read("../../../packages/image/tests/resources/disk-a/kitten-1.jpg")?;
let mut image = Image::new(&blob)?;
let focal = FocalPoint::from_parts(Some(0.3), Some(0.2))?;
image.crop(300, 100, Gravity::Center, focal)?;
let webp = image.output(OutputFormat::Webp, 75)?;
assert_eq!(&webp[8..12], b"WEBP");
PHP
use Utopia\Image\Image;

$image = new Image(file_get_contents('/usr/src/code/packages/image/tests/resources/disk-a/kitten-1.jpg'));
$image->crop(300, 100, Image::GRAVITY_CENTER, x: 0.3, y: 0.2);
echo substr($image->output('webp', 75), 8, 4), "\n"; // WEBP

Decorate it

Borders, rounded corners, opacity, rotation and a background colour chain like the PHP setters. Colours are ImageMagick colour strings.

Rust
use utopia_image::{Image, OutputFormat};

let blob = std::fs::read("../../../packages/image/tests/resources/resize/100x100.png")?;
let mut image = Image::new(&blob)?;
image.set_opacity(0.5).set_rotation(90)?.set_background("#ffffff")?;
let png = image.output(OutputFormat::Png, 100)?;
assert_eq!(&png[1..4], b"PNG");
PHP
use Utopia\Image\Image;

$image = new Image(file_get_contents('/usr/src/code/packages/image/tests/resources/resize/100x100.png'));
$image->setOpacity(0.5)->setRotation(90)->setBackground('#ffffff');
echo substr($image->output('png', 100), 1, 3), "\n"; // PNG

Save it to disk

save creates the directory when it is missing; a known file extension decides the format.

Rust
use utopia_image::{Image, OutputFormat};

let blob = std::fs::read("../../../packages/image/tests/resources/resize/100x100.png")?;
let dir = std::env::temp_dir().join("utopia-image-guide");
Image::new(&blob)?.save(dir.join("preview.gif"), OutputFormat::Gif, 75)?;
assert!(dir.join("preview.gif").exists());
PHP
use Utopia\Image\Image;

$dir = sys_get_temp_dir() . '/utopia-image-guide';
(new Image(file_get_contents('/usr/src/code/packages/image/tests/resources/resize/100x100.png')))->save("$dir/preview.gif", 'gif', 75);
var_dump(file_exists("$dir/preview.gif")); // bool(true)

Reference#

Image previews: decode a JPEG, PNG, GIF or WebP (animations included), crop it by gravity or focal point, add a border, round its corners, change its opacity, rotate it, flatten it onto a background, and encode it as JPEG, PNG, GIF, WebP or AVIF.

All the work is CPU-bound: in async code run it on the blocking pool (utopia_async::spawn_blocking), never on a runtime thread.

The codecs are pure Rust by default. Next to ImageMagick, which the PHP library wraps, that means: WebP is written lossless (no pure-Rust lossy VP8 encoder exists), AVIF is written but not read, and HEIC is neither read nor written. Two features add those through the C libraries ImageMagick itself uses: libwebp writes lossy WebP at the requested quality, and libheif reads AVIF and HEIC, writes AVIF as ImageMagick does, and writes HEIC where the system's libheif has an HEVC encoder (Appwrite's PHP image has none, so HEIC output fails there in PHP too). The pure-Rust AVIF encoder is the default ravif feature; a process that forks, such as a PHP extension under Swoole, leaves it out and writes AVIF through libheif. Pixels match ImageMagick's up to resampling and encoder differences; sizes, frames, delays and formats match exactly.

PHP → Rust:

PHP (Utopia\Image)Rust (utopia_image)
Canvas: new Canvas($data, $limits), new Canvas(new Blank(...))[Canvas]: Canvas::decode, Canvas::blank
$canvas->width, ->height, ->orientation, ->formatCanvas::width, Canvas::height, Canvas::orientation, Canvas::format
apply(Transform)Canvas::apply with Transform
draw(Path|Text)Canvas::draw with Drawing
encode(Format, ?int $quality)Canvas::encode with OutputFormat
LimitsLimits
Gravity, PointGravity, FocalPoint
Font::has($character)has_glyph
colour strings (ImagickPixel)Color
Exception\ImageException and its UnsupportedFormatException, CorruptImageException and LimitExceededException; InvalidArgumentException, DivisionByZeroErrorError
Rust
use utopia_image::{Gravity, Image, OutputFormat};

let jpeg = std::fs::read("../../../packages/image/tests/resources/resize/100x100.jpg")?;
let mut image = Image::new(&jpeg)?;
image.crop(64, 64, Gravity::Center, None)?.set_border_radius(8)?;
let png = image.output(OutputFormat::Png, 90)?;
assert_eq!(&png[1..4], b"PNG");
PHP
use Utopia\Image\Image;

$image = new Image(file_get_contents('/usr/src/code/packages/image/tests/resources/resize/100x100.jpg'));
$image->crop(64, 64)->setBorderRadius(8);
echo substr($image->output('png', 90), 1, 3), "\n"; // PNG

API#

What utopia_image exports at its root.