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"; // ffd8ffImplementations§
Source§impl Image
impl Image
Sourcepub fn new(data: &[u8]) -> Result<Image>
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).
Sourcepub fn blank(width: u32, height: u32, background: &str) -> Result<Image>
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");Sourcepub fn orientation(&self) -> u32
pub fn orientation(&self) -> u32
The EXIF orientation the image was read with (1 to 8; 1 when it had none).
PHP: getOrientation().
Sourcepub fn fill_path(
&mut self,
path: &str,
color: &str,
x: f64,
y: f64,
scale: f64,
) -> Result<&mut Self>
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).
Sourcepub fn draw_text(
&mut self,
text: &str,
font: &[u8],
size: f64,
color: &str,
x: f64,
y: f64,
) -> Result<&mut Self>
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.
Sourcepub fn width(&self) -> i64
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).
Sourcepub fn crop(
&mut self,
width: u32,
height: u32,
gravity: Gravity,
focal: Option<FocalPoint>,
) -> Result<&mut Self>
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);Sourcepub fn set_border(&mut self, width: u32, color: &str) -> Result<&mut Self>
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.
Sourcepub fn set_border_radius(&mut self, radius: u32) -> Result<&mut Self>
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).
Sourcepub fn set_opacity(&mut self, opacity: f64) -> &mut Self
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).
Sourcepub fn set_rotation(&mut self, degrees: i64) -> Result<&mut Self>
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).
Sourcepub fn set_background(&mut self, color: &str) -> Result<&mut Self>
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.
Sourcepub fn output(&mut self, format: OutputFormat, quality: i64) -> Result<Vec<u8>>
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"; // WEBPSourcepub fn save(
&mut self,
path: impl AsRef<Path>,
format: OutputFormat,
quality: i64,
) -> Result<()>
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).
Sourcepub fn size_by_fixed_height(&self, height: i64) -> Result<i64>
pub fn size_by_fixed_height(&self, height: i64) -> Result<i64>
The width that keeps the aspect ratio at height.
PHP: getSizeByFixedHeight($newHeight) (protected).
Sourcepub fn size_by_fixed_width(&self, width: i64) -> Result<i64>
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§
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> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> ErasedDestructor for Twhere
T: 'static,
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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