Skip to main content

Image

Struct Image 

Source
pub struct Image { /* private fields */ }
Expand description

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"; // ffd8ff

Implementations§

Source§

impl Image

Source

pub fn new(data: &[u8]) -> Result<Image>

Decodes a JPEG, PNG, GIF or WebP blob, every frame of an animation, and reads its EXIF orientation (3, 6 and 8 rotate the image when it is written; mirrored orientations are ignored).

The format is read from the signature first (Format::detect): anything but JPEG, PNG, GIF, WebP, AVIF and HEIC fails with Error::UnsupportedFormat before a decoder sees it.

PHP: new Image($data).

Source

pub fn blank(width: u32, height: u32, background: &str) -> Result<Image>

A width x height image of one colour, written as PNG unless another format is asked for.

PHP: Image::create($width, $height, $background).

use utopia_image::{Image, OutputFormat};

let mut image = Image::blank(64, 64, "#e5e5e5")?;
image.fill_path("M0 0h10v10h-10Z", "#333333", 27.0, 27.0, 1.0)?;
assert_eq!(&image.output(OutputFormat::Png, 75)?[1..4], b"PNG");
Source

pub fn orientation(&self) -> u32

The EXIF orientation the image was read with (1 to 8; 1 when it had none).

PHP: getOrientation().

Source

pub fn fill_path( &mut self, path: &str, color: &str, x: f64, y: f64, scale: f64, ) -> Result<&mut Self>

Fills SVG path data with color on the current frame, scaled by scale and then moved by x and y.

PHP: path($path, $color, $x, $y, $scale).

Source

pub fn draw_text( &mut self, text: &str, font: &[u8], size: f64, color: &str, x: f64, y: f64, ) -> Result<&mut Self>

Draws text on the current frame in font (TrueType or OpenType data) at size pixels an em, centred on x with its baseline at y.

PHP: text($text, $font, $size, $color, $x, $y), where $font is a path.

Source

pub fn width(&self) -> i64

The width the operations work from: the decoded width, then the last crop’s (borders and rotations do not change it, as in PHP).

Source

pub fn height(&self) -> i64

The height the operations work from (see width).

Source

pub fn frames(&self) -> usize

The number of frames.

Source

pub fn crop( &mut self, width: u32, height: u32, gravity: Gravity, focal: Option<FocalPoint>, ) -> Result<&mut Self>

Crops to width x height.

Without a focal point and with Gravity::Center, the image is scaled to cover the target and its centre is kept (a thumbnail crop). With another gravity or a focal point, it is scaled to cover the target and the rectangle at that gravity, or centred on the point as far as the edges allow, is kept. A zero width or height follows the aspect ratio; both zero keep the size. Every frame of an animation is cropped.

PHP: crop($width, $height, $gravity, $x, $y).

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

let png = std::fs::read("../../../packages/image/tests/resources/resize/100x100.png")?;
let mut image = Image::new(&png)?;
image.crop(40, 20, Gravity::Center, Some(FocalPoint::new(0.25, 0.75)?))?;
assert_eq!((image.width(), image.height()), (40, 20));
use Utopia\Image\Image;

$image = new Image(file_get_contents('/usr/src/code/packages/image/tests/resources/resize/100x100.png'));
$image->crop(40, 20, Image::GRAVITY_CENTER, x: 0.25, y: 0.75);
Source

pub fn set_border(&mut self, width: u32, color: &str) -> Result<&mut Self>

Adds a width-pixel border of color around the current frame (see Color for the strings accepted). The border is also what set_border_radius strokes.

PHP: setBorder($borderWidth, $borderColor). The width and colour are remembered before the colour is parsed, as in PHP.

Source

pub fn set_border_radius(&mut self, radius: u32) -> Result<&mut Self>

Rounds the corners of the current frame with radius: outside the rounded rectangle pixels turn transparent, or black on an image without an alpha channel (a JPEG). With a border set, the rectangle is inset by it and stroked with its colour, and the image becomes that one frame.

PHP: setBorderRadius($cornerRadius).

Source

pub fn set_opacity(&mut self, opacity: f64) -> &mut Self

Sets the opacity of the current frame: every pixel’s alpha becomes opacity of opaque (existing transparency is replaced). 1.0 changes nothing; values past 0..=1 clamp, NaN is transparent.

PHP: setOpacity($opacity).

Source

pub fn set_rotation(&mut self, degrees: i64) -> Result<&mut Self>

Rotates the current frame clockwise by degrees, filling with transparency; the canvas grows to fit.

PHP: setRotation($degree).

Source

pub fn set_background(&mut self, color: &str) -> Result<&mut Self>

Flattens every frame onto color (see Color), leaving one frame.

PHP: setBackground($color). The colour is set on the current frame but the flattening uses the first frame’s, as in PHP.

Source

pub fn output(&mut self, format: OutputFormat, quality: i64) -> Result<Vec<u8>>

Encodes the image as format with quality (0–100; negative leaves the encoder’s default), applying the pending EXIF rotation first (once).

PHP: output($type, $quality).

use utopia_image::{Image, OutputFormat};

let png = std::fs::read("../../../packages/image/tests/resources/resize/100x100.png")?;
let webp = Image::new(&png)?.output("webp".parse::<OutputFormat>()?, 75)?;
assert_eq!(&webp[8..12], b"WEBP");
use Utopia\Image\Image;

$image = new Image(file_get_contents('/usr/src/code/packages/image/tests/resources/resize/100x100.png'));
echo substr($image->output('webp', 75), 8, 4), "\n"; // WEBP
Source

pub fn save( &mut self, path: impl AsRef<Path>, format: OutputFormat, quality: i64, ) -> Result<()>

Writes the image to path, creating its directory (mode 0755) when missing. A recognised file extension (.png, .jpg, …) decides the format over format, as ImageMagick does.

PHP: save($path, $type, $quality).

Source

pub fn size_by_fixed_height(&self, height: i64) -> Result<i64>

The width that keeps the aspect ratio at height.

PHP: getSizeByFixedHeight($newHeight) (protected).

Source

pub fn size_by_fixed_width(&self, width: i64) -> Result<i64>

The height that keeps the aspect ratio at width.

PHP: getSizeByFixedWidth($newWidth) (protected).

Trait Implementations§

Source§

impl Clone for Image

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Image

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Forget for Image

§

impl Freeze for Image

§

impl Move for Image

§

impl RefUnwindSafe for Image

§

impl Send for Image

§

impl Sync for Image

§

impl Unpin for Image

§

impl UnsafeUnpin for Image

§

impl UnwindSafe for Image

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.