Contents
use utopia_image::Canvas;pub struct Canvas {
// private fields
}An image, and what has been asked of it so far.
A canvas is immutable: apply and draw
return a new one that shares the source bytes. Steps run in the order they
were added, each on what the one before it left. Nothing is decoded until
encode, which decodes, runs every step and writes the
result in one pass. The size, format and orientation come from the header.
PHP: Utopia\Image\Canvas.
use utopia_image::{Canvas, Limits, OutputFormat, Transform};
let png = std::fs::read("../../../packages/image/tests/resources/resize/100x100.png")?;
let canvas = Canvas::decode(&png, Limits::default())?;
assert_eq!((canvas.width(), canvas.height()), (100, 100));
let jpeg = canvas.apply(Transform { width: 50, height: 25, ..Transform::default() })?.encode(OutputFormat::Jpeg, Some(80))?;
assert_eq!(&jpeg[..3], &[0xFF, 0xD8, 0xFF]);use utopia_image::Color;pub struct Color(pub [u8; 4]);An RGBA colour with 8 bits per channel (alpha 255 is opaque).
Parsed from the strings ImageMagick accepts for borders and backgrounds:
#rgb, #rgba, #rrggbb, #rrggbbaa, rgb(r, g, b), rgba(r, g, b, a)
(channels as 0–255 or percentages, alpha as 0–1), the CSS colour names,
transparent and none. The empty string is ImageMagick's background
colour, white.
PHP: the $borderColor of setBorder() and the $color of
setBackground(), which Imagick parses with QueryColorCompliance.
use utopia_image::Color;
assert_eq!(Color::parse("#ff000080")?, Color::rgba(255, 0, 0, 128));
assert_eq!(Color::parse("red")?, Color::rgba(255, 0, 0, 255));
assert!(Color::parse("notacolor").is_err());$pixel = new \ImagickPixel('#ff000080');
print_r($pixel->getColor(1)); // r 1, g 0, b 0, a 0.5use utopia_image::FocalPoint;pub struct FocalPoint {
// private fields
}A focal point: the spot a crop keeps in view, as fractions of the width
and height (0.0..=1.0).
PHP: the $x and $y arguments of crop().
use utopia_image::FocalPoint;
let point = FocalPoint::new(0.75, 0.5)?;
assert_eq!((point.x(), point.y()), (0.75, 0.5));
assert!(FocalPoint::new(1.1, 0.5).is_err());
assert!(FocalPoint::from_parts(Some(0.5), None).is_err());
assert_eq!(FocalPoint::from_parts(None, None)?, None);use Utopia\Image\Image;
$source = new \Imagick();
$source->newImage(6, 2, 'red', 'png');
$image = new Image($source->getImageBlob());
$image->crop(2, 2, x: 0.75, y: 0.5);
try {
$image->crop(2, 2, x: 1.1, y: 0.5);
} catch (\InvalidArgumentException $e) {
echo $e->getMessage(), "\n";
}use utopia_image::Image;pub struct Image {
// private fields
}A decoded image (every frame of an animation), transformed in place and
encoded on output or save.
Every method is CPU-bound and can take tens of milliseconds on a large
image: in async code, run the whole pipeline on the blocking pool
(utopia_async::spawn_blocking).
Like ImageMagick, an image tracks a current frame: the first after decoding, the last after cropping an animation. Borders, rounded corners, opacity, rotation and the output format apply to the current frame only, and an animation is written in its first frame's format. These are kept from PHP as quirks.
PHP: Utopia\Image\Image.
use utopia_image::{Gravity, Image, OutputFormat};
let png = std::fs::read("../../../packages/image/tests/resources/resize/100x100.png")?;
let mut image = Image::new(&png)?;
image.crop(50, 25, Gravity::Top, None)?.set_border(2, "#ff0000")?;
let jpeg = image.output(OutputFormat::Jpeg, 80)?;
assert_eq!(&jpeg[..3], &[0xFF, 0xD8, 0xFF]);use Utopia\Image\Image;
$image = new Image(file_get_contents('/usr/src/code/packages/image/tests/resources/resize/100x100.png'));
$image->crop(50, 25, Image::GRAVITY_TOP)->setBorder(2, '#ff0000');
echo bin2hex(substr($image->output('jpg', 80), 0, 3)), "\n"; // ffd8ffuse utopia_image::Limits;pub struct Limits {
pub width: u64,
pub height: u64,
pub memory: u64,
}What one image may cost: its largest width and height in pixels, and how many bytes of decoded pixels it may hold at once.
The defaults are conservative (16,000 pixels a side, 512 MiB of pixels); a caller that wants more says so. There is no "unlimited".
PHP: Utopia\Image\Limits.
use utopia_image::Limits;
let limits = Limits { width: 4_000, ..Limits::default() };
assert_eq!(limits.height, 16_000);Default.use utopia_image::Transform;pub struct Transform {
pub width: u32,
pub height: u32,
pub gravity: Gravity,
pub focus: Option<FocalPoint>,
pub opacity: f64,
pub background: Option<String>,
pub border: Option<(u32, String)>,
pub radius: u32,
pub rotation: i64,
}One preview: a crop, then opacity, a background, a border, rounded corners and a rotation, in that order. A part left at its default is skipped.
PHP: Utopia\Image\Transform.
Default.use utopia_image::Drawing;pub enum Drawing {
Path {
data: String,
color: String,
x: f64,
y: f64,
scale: f64,
},
Text {
text: String,
font: Arc<[u8]>,
size: f64,
color: String,
x: f64,
y: f64,
},
}Something drawn onto a canvas.
use utopia_image::Error;pub enum Error {
UnsupportedFormat(String),
Corrupt(String),
LimitExceeded,
InvalidArgument(String),
DivisionByZero,
Failed(String),
}Everything Image can fail with, one variant per PHP
exception class. The messages are the library's own and say what the
caller can act on; what a codec reported is kept for Debug only.
PHP: Utopia\Image\Exception\ImageException and its subclasses for what an
image or the system makes fail, and \InvalidArgumentException for an
argument that could never work.
use utopia_image::Format;pub enum Format {
Jpeg,
Png,
Gif,
Webp,
Avif,
Heic,
}A raster format Image::new accepts, identified
from the file signature, so only decoders for these formats ever see the
data.
PHP: Utopia\Image\Format (a string-backed enum).
use utopia_image::Format;
assert_eq!(Format::detect(b"\x89PNG\r\n\x1a\n")?, Format::Png);
assert_eq!(Format::Png.value(), "PNG");
assert!(Format::detect(b"P3\n1 1\n255\n").is_err());use Utopia\Image\Format;
echo Format::detect("\x89PNG\r\n\x1A\n")->value, "\n"; // PNG
try {
Format::detect("P3\n1 1\n255\n");
} catch (\Utopia\Image\Exception\UnsupportedFormatException $e) {
echo $e->getMessage(), "\n";
}use utopia_image::Gravity;pub enum Gravity {
Center,
TopLeft,
Top,
TopRight,
Left,
Right,
BottomLeft,
Bottom,
BottomRight,
}Which part of the image a crop keeps.
PHP: the Image::GRAVITY_* string constants.
use utopia_image::Gravity;
assert_eq!(Gravity::from_name("top-left"), Some(Gravity::TopLeft));
assert_eq!(Gravity::TopLeft.name(), "top-left");
assert_eq!(Gravity::ALL.len(), 9);use Utopia\Image\Image;
echo Image::GRAVITY_TOP_LEFT, "\n"; // top-left
echo count(Image::getGravityTypes()), "\n"; // 9use utopia_image::OutputFormat;pub enum OutputFormat {
Jpeg,
Gif,
Png,
Webp,
Avif,
Heic,
}An output format.
PHP: the $type string of output() and save(); jpg and jpeg are
the same format.
use utopia_image::OutputFormat;
assert_eq!("jpeg".parse::<OutputFormat>()?, OutputFormat::Jpeg);
assert_eq!("bmp".parse::<OutputFormat>().unwrap_err().to_string(), "Unsupported output format: bmp");use Utopia\Image\Image;
$source = new \Imagick();
$source->newImage(2, 2, 'red', 'png');
try {
(new Image($source->getImageBlob()))->output('bmp');
} catch (\Exception $e) {
echo $e->getMessage(), "\n"; // Invalid output type given
}FromStr.use utopia_image::has_glyph;pub fn has_glyph(font: &[u8], character: char) -> Result<bool>Whether font (TrueType or OpenType data) draws something for character:
a missing glyph, or one with no outline, draws nothing.
pub type Result<T> = Result<T, Error>;The result of every fallible operation of this crate.