pub struct Image { /* private fields */ }Expand description
Represents a single image
Implementations§
Source§impl Image
impl Image
Sourcepub fn save<P: AsRef<Path>>(&self, file: P) -> Result<(), ImageErrors>
pub fn save<P: AsRef<Path>>(&self, file: P) -> Result<(), ImageErrors>
Save the image to a file and use the extension to determine the format
If the extension cannot be determined from the path, it’s an error.
§Arguments
file: The file to save the image to
returns: Result<(), ImageErrors>
§Examples
- Encode image to jpeg format, requires
jpegfeature
use zune_core::colorspace::ColorSpace;
use zune_image::image::Image;
// create a luma image
let image = Image::fill::<u8>(128,ColorSpace::Luma,100,100);
// save to jpeg
image.save("hello.jpg").unwrap();Sourcepub fn save_to<P: AsRef<Path>>(
&self,
file: P,
format: ImageFormat,
) -> Result<(), ImageErrors>
pub fn save_to<P: AsRef<Path>>( &self, file: P, format: ImageFormat, ) -> Result<(), ImageErrors>
Save an image using a specified format to a file
The image may be cloned and the clone modified to fit preferences for that specific image format, e.g if the image is in f32 and being saved to jpeg, the clone will be modified to be in u8, and that will be the format saved to jpeg.
§Arguments
file: The file path to which the image will be savedformat: The format to save the image into. It’s an error if the format doesn’t have an encoder(not all formats do)
returns: Result<(), ImageErrors>
§Examples
- Save a black grayscale image to JPEG, requires the JPEG feature
use zune_core::colorspace::ColorSpace;
use zune_image::codecs::ImageFormat;
use zune_image::errors::ImageErrors;
use zune_image::image::Image;
fn main()->Result<(),ImageErrors>{
// create a simple 200x200 grayscale image consisting of pure black
let image = Image::fill::<u8>(0,ColorSpace::Luma,200,200);
// save that to jpeg
#[cfg(feature = "jpeg")]
{
image.save_to("black.jpg",ImageFormat::JPEG)?;
}
Ok(())
}Sourcepub fn write_to_vec(&self, format: ImageFormat) -> Result<Vec<u8>, ImageErrors>
pub fn write_to_vec(&self, format: ImageFormat) -> Result<Vec<u8>, ImageErrors>
Encode an image returning a vector containing the result of the encoding
§Arguments
format: The format to use for encoding, it’s an error if the relevant encoder is not present either because it’s not supported, or it’s not included as a feature.
returns: Result<Vec<u8, Global>, ImageErrors>
§Examples
- Encode a simple image to QOI format, needs qoi format to be enabled
use zune_core::colorspace::ColorSpace;
use zune_image::codecs::ImageFormat;
use zune_image::image::Image;
// create an image using from fn, to generate a gradient image
let image = Image::from_fn::<u8,_>(300,300,ColorSpace::RGB,|x,y,px|{
let r = (0.3 * x as f32) as u8;
let b = (0.3 * y as f32) as u8;
px[0] = r;
px[2] = b;
});
// write to qoi now
let contents = image.write_to_vec(ImageFormat::QOI).unwrap();Sourcepub fn write_with_encoder<T: ZByteWriterTrait>(
&self,
encoder: impl EncoderTrait,
sink: T,
) -> Result<usize, ImageErrors>
pub fn write_with_encoder<T: ZByteWriterTrait>( &self, encoder: impl EncoderTrait, sink: T, ) -> Result<usize, ImageErrors>
Write data to a sink using a custom encoder returning how many bytes were written if successful
§Arguments
encoder: The encoder to use for encodingsink: Where does output data goes
returns: Result<usize, ImageErrors>
§Examples
- Encode a simple image to JPEG format
use zune_core::colorspace::ColorSpace;
// requires jpeg feature
use zune_image::codecs::jpeg::JpegEncoder;
use zune_image::image::Image;
let encoder = JpegEncoder::new();
// create an image using from fn, to generate a gradient image
let image = Image::from_fn::<u8,_>(300,300,ColorSpace::RGB,|x,y,px|{
let r = (0.3 * x as f32) as u8;
let b = (0.3 * y as f32) as u8;
px[0] = r;
px[2] = b;
});
let mut output = vec![];
// write to jpeg now
let contents = image.write_with_encoder(encoder, &mut output).unwrap();Sourcepub fn open<P: AsRef<Path>>(file: P) -> Result<Image, ImageErrors>
pub fn open<P: AsRef<Path>>(file: P) -> Result<Image, ImageErrors>
Open an encoded file for which the library has a configured decoder for it
- The decoders supported can be switched on and off depending on how you configure your Cargo.toml. It is generally recommended to not enable decoders you will not be using as it reduces both the security attack surface and dependency
§Arguments
- file: The file path from which to read the file from, the file must be a supported format otherwise it’s an error to try and decode
See also read for reading from memory
Sourcepub fn open_with_options<P: AsRef<Path>>(
file: P,
options: DecoderOptions,
) -> Result<Image, ImageErrors>
pub fn open_with_options<P: AsRef<Path>>( file: P, options: DecoderOptions, ) -> Result<Image, ImageErrors>
Open an encoded file for which the library has a configured decoder for it with the specified custom decoder options
This allows you to modify decoding steps where possible by specifying how the decoder should behave
§Example
- Decode a file with strict mode enabled and only expect images with less than 100 pixels in width
use zune_core::options::DecoderOptions;
use zune_image::image::Image;
let options = DecoderOptions::default().set_strict_mode(true).set_max_width(100);
let image = Image::open_with_options("/a/file.jpeg",options).unwrap();Sourcepub fn read<T>(src: T, options: DecoderOptions) -> Result<Image, ImageErrors>
pub fn read<T>(src: T, options: DecoderOptions) -> Result<Image, ImageErrors>
Open a new file from memory with the configured options
§Arguments
src: The encoded buffer loaded into memoryoptions: The configured decoded options
§Example
- Open a memory source with the default options
use zune_core::bytestream::ZCursor;
use zune_core::options::DecoderOptions;
use zune_image::image::Image;
// create a simple ppm p5 grayscale format
let image = Image::read(ZCursor::new(b"P5 1 1 255 1"),DecoderOptions::default());Sourcepub fn encode<T: ZByteWriterTrait>(
&self,
format: ImageFormat,
sink: T,
) -> Result<usize, ImageErrors>
pub fn encode<T: ZByteWriterTrait>( &self, format: ImageFormat, sink: T, ) -> Result<usize, ImageErrors>
Sourcepub fn from_decoder(decoder: impl DecoderTrait) -> Result<Image, ImageErrors>
pub fn from_decoder(decoder: impl DecoderTrait) -> Result<Image, ImageErrors>
Open a new file from memory with the configured decoder
§Arguments
decoder: The configured decoder
§Example
- Open a memory source with the ppm decoder
// requires ppm feature
use std::io::Cursor;
use zune_image::codecs::ppm::PPMDecoder;
use zune_image::image::Image;
// create a simple ppm p5 grayscale format
let decoder = PPMDecoder::new(Cursor::new(b"P5 1 1 255 1"));
let image = Image::from_decoder(decoder);Source§impl Image
impl Image
Sourcepub fn new(
channels: Vec<Channel>,
depth: BitDepth,
width: usize,
height: usize,
colorspace: ColorSpace,
) -> Image
pub fn new( channels: Vec<Channel>, depth: BitDepth, width: usize, height: usize, colorspace: ColorSpace, ) -> Image
Create a new image instance
This constructs a single image frame (non-animated) with the configured dimensions,colorspace and depth
Sourcepub fn new_frames(
frames: Vec<Frame>,
depth: BitDepth,
width: usize,
height: usize,
colorspace: ColorSpace,
) -> Image
pub fn new_frames( frames: Vec<Frame>, depth: BitDepth, width: usize, height: usize, colorspace: ColorSpace, ) -> Image
Create an image from multiple frames.
Sourcepub fn is_animated(&self) -> bool
pub fn is_animated(&self) -> bool
Return true if the current image contains more than one frame indicating it is animated
§Returns
- true : Image contains a series of frames which can be animated
- false: Image contains a single frame
Sourcepub const fn dimensions(&self) -> (usize, usize)
pub const fn dimensions(&self) -> (usize, usize)
Get image dimensions as a tuple of (width,height)
Sourcepub fn set_depth(&mut self, depth: BitDepth)
pub fn set_depth(&mut self, depth: BitDepth)
Set image depth
Ensure that the image is in a certain depth before changing this otherwise bad things will happen
Sourcepub const fn metadata(&self) -> &ImageMetadata
pub const fn metadata(&self) -> &ImageMetadata
Return an immutable reference to the metadata of the image
Sourcepub fn metadata_mut(&mut self) -> &mut ImageMetadata
pub fn metadata_mut(&mut self) -> &mut ImageMetadata
Return a mutable reference to the image metadata.
Do not modify elements like width and height anyhowly, it may corrupt the image in ways only God knows
Sourcepub fn frames_ref(&self) -> &[Frame]
pub fn frames_ref(&self) -> &[Frame]
Sourcepub fn frames_mut(&mut self) -> &mut [Frame]
pub fn frames_mut(&mut self) -> &mut [Frame]
Return a mutable reference to all image frames.
Sourcepub fn channels_ref(&self, ignore_alpha: bool) -> Vec<&Channel>
pub fn channels_ref(&self, ignore_alpha: bool) -> Vec<&Channel>
Return a reference to the underlying channels
Sourcepub fn channels_mut(&mut self, ignore_alpha: bool) -> Vec<&mut Channel>
pub fn channels_mut(&mut self, ignore_alpha: bool) -> Vec<&mut Channel>
Return a mutable view into the image channels
This gives mutable access to the chanel data allowing single or multithreaded manipulation of images
Sourcepub const fn colorspace(&self) -> ColorSpace
pub const fn colorspace(&self) -> ColorSpace
Get the colorspace this image is stored in
Sourcepub fn flatten_frames<T: Default + Copy + 'static + Pod>(&self) -> Vec<Vec<T>>
pub fn flatten_frames<T: Default + Copy + 'static + Pod>(&self) -> Vec<Vec<T>>
Flatten channels in this image.
Flatten can be used to interleave all channels into one vector
Sourcepub fn flatten_to_u8(&self) -> Vec<Vec<u8>>
pub fn flatten_to_u8(&self) -> Vec<Vec<u8>>
Convert the images to
Sourcepub fn set_dimensions(&mut self, width: usize, height: usize)
pub fn set_dimensions(&mut self, width: usize, height: usize)
Sourcepub fn fill<T>(
pixel: T,
colorspace: ColorSpace,
width: usize,
height: usize,
) -> Image
pub fn fill<T>( pixel: T, colorspace: ColorSpace, width: usize, height: usize, ) -> Image
Create an image with a static color in it
§Arguments
- pixel: Value to fill the image with
- colorspace: The image colorspace
- width: Image width
- height: Image height
§Supported Types
- u8: BitDepth is treated as BitDepth::Eight
- u16: BitDepth is treated as BitDepth::Sixteen
- f32: BitDepth is treated as BitDepth::Float32
§Example
- Create a 800 by 800 RGB image of type u8
use zune_core::colorspace::ColorSpace;
use zune_image::image::Image;
let image = Image::fill::<u8>(212,ColorSpace::RGB,800,800);Sourcepub fn from_fn<T, F>(
width: usize,
height: usize,
colorspace: ColorSpace,
func: F,
) -> Image
pub fn from_fn<T, F>( width: usize, height: usize, colorspace: ColorSpace, func: F, ) -> Image
Create an image from a function
The image width , height and colorspace need to be specified
The function will receive two parameters, the first is the current x offset and y offset
and for each it’s expected to return an array with MAX_CHANNELS
§Arguments
- width : The width of the new image
- height: The height of the new image
- colorspace: The new colorspace of the image
- func: A function which will be called for every pixel position
the function is supposed to return pixels for that position
- y: The position in the y-axis, starts at 0, ends at image height
- x: The position in the x-axis, starts at 0, ends at image width
- pixels: A mutable region where you can write pixels to. The results will be copied to the pixel positions at pixel x,y for image channels
§Limitations.
Due to constrains imposed by the library, the response has to be an array containing MAX_CHANNELS, depending on the number of components the colorspace uses some elements may be ignored.
E.g for the following code
use zune_core::colorspace::ColorSpace;
use zune_image::image::{Image, MAX_CHANNELS};
fn linear_gradient(y:usize,x:usize,pixels:&mut [u8;MAX_CHANNELS])
{
// this will create a linear band of colors from black to white and repeats
// until the whole image is visited
let luma = ((x+y) % 256) as u8;
pixels[0] = luma;
}
let img = Image::from_fn(30,20,ColorSpace::Luma,linear_gradient);We only set one element in our array but need to return an array with MAX_CHANNELS elements
Source§impl Image
Pixel constructors
impl Image
Pixel constructors
Sourcepub fn from_u8(
pixels: &[u8],
width: usize,
height: usize,
colorspace: ColorSpace,
) -> Image
pub fn from_u8( pixels: &[u8], width: usize, height: usize, colorspace: ColorSpace, ) -> Image
Create a new image from a raw pixels
The image depth is treated as BitDepth::U8 and formats which pack images into lower bit-depths are expected to expand them before using this function
Pixels are expected to be interleaved according to the colorspace
I.e if the image is RGB, pixel layout should be [R,G,B,R,G,B]
if it’s Luma with alpha, pixel layout should be [L,A,L,A]
§Returns
An Image struct
§Panics
-
In case calculating image dimensions overflows a
usizethis indicates that the array cannot be indexed by usize,hence values are invalid -
If the length of pixels doesn’t match the expected length
Sourcepub fn from_u16(
pixels: &[u16],
width: usize,
height: usize,
colorspace: ColorSpace,
) -> Image
pub fn from_u16( pixels: &[u16], width: usize, height: usize, colorspace: ColorSpace, ) -> Image
Create an image from raw u16 pixels
Pixels are expected to be interleaved according to number of components in the colorspace
e.g if image is RGBA, pixels should be in the form of [R,G,B,A,R,G,B,A]
The bit depth will be treated as BitDepth::Sixteen
§Returns
An Image struct
§Panics
-
If calculating image dimensions will overflow
usize -
If pixels length is not equal to expected length
Sourcepub fn from_f32(
pixels: &[f32],
width: usize,
height: usize,
colorspace: ColorSpace,
) -> Image
pub fn from_f32( pixels: &[f32], width: usize, height: usize, colorspace: ColorSpace, ) -> Image
Create an image from raw f32 pixels
Pixels are expected to be interleaved according to number of components in the colorspace
e.g if image is RGBA, pixels should be in the form of [R,G,B,A,R,G,B,A]
The bit depth will be treated as BitDepth::Float32
§Returns
An Image struct
§Panics
-
If calculating image dimensions will overflow
usize -
If pixels length is not equal to expected length
pub fn frames_len(&self) -> usize
Source§impl Image
Pixel manipulation methods
impl Image
Pixel manipulation methods
Sourcepub fn modify_pixels_mut<T, F>(&mut self, func: F) -> Result<(), ChannelErrors>
pub fn modify_pixels_mut<T, F>(&mut self, func: F) -> Result<(), ChannelErrors>
Modify pixels in place using function func
This iterates through all frames in the channel and calls a function on each mutable pixel
§Arguments
- func: Function which will modify the pixels
The arguments used are
y: usize, the current position of the height we are currently inx: usize, the current position on the x axis we are in[&mut T;MAX_CHANNELS], the pixels at[y,x]from the channels which can be modified. Even though it returnsMAX_CHANNELS, only the image colorspace components considered, so for Luma colorspace, we only use the first element in the array and the rest are ignored
§Returns
- Ok(()): Successful manipulation of image
- Err(ChannelErrors): The channel could not be converted to type
T
§Example
Modify pixels creating a gradient
use zune_core::colorspace::ColorSpace;
use zune_image::image::Image;
// fill image with black pixel
let mut image = Image::fill(0_u8,ColorSpace::RGB,800,800);
// then modify the pixels
// create a gradient
image.modify_pixels_mut(|x,y,pix|
{
let r = (0.3 * x as f32) as u8;
let b = (0.3 * y as f32) as u8;
// modify channels directly
*pix[0] = r;
*pix[2] = b;
}).unwrap();
Source§impl Image
Image conversion routines
impl Image
Image conversion routines
Sourcepub fn convert_color(&mut self, to: ColorSpace) -> Result<(), ImageErrors>
pub fn convert_color(&mut self, to: ColorSpace) -> Result<(), ImageErrors>
Sourcepub fn convert_depth(&mut self, to: BitDepth) -> Result<(), ImageErrors>
pub fn convert_depth(&mut self, to: BitDepth) -> Result<(), ImageErrors>
Trait Implementations§
impl Eq for Image
Auto Trait Implementations§
impl Freeze 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,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
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