Skip to main content

Image

Struct Image 

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

Represents a single image

Implementations§

Source§

impl Image

Source

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 jpeg feature
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();
Source

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 saved
  • format: 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(())
}
Source

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();
Source

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 encoding
  • sink: 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();
Source

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

Source

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();
Source

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 memory
  • options: 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());
Source

pub fn encode<T: ZByteWriterTrait>( &self, format: ImageFormat, sink: T, ) -> Result<usize, ImageErrors>

Encode to a generic sink an image of a specific format

§Arguments
  • format: The image format to write to sink
  • sink: An encapsulation of where we will be sending data to
§Returns
  • The size of bytes written to sink or an error if it occurs
Source

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

Source

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

Source

pub fn new_frames( frames: Vec<Frame>, depth: BitDepth, width: usize, height: usize, colorspace: ColorSpace, ) -> Image

Create an image from multiple frames.

Source

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
Source

pub const fn dimensions(&self) -> (usize, usize)

Get image dimensions as a tuple of (width,height)

Source

pub const fn depth(&self) -> BitDepth

Get the image depth of this image

Source

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

Source

pub const fn metadata(&self) -> &ImageMetadata

Return an immutable reference to the metadata of the image

Source

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

Source

pub fn frames_ref(&self) -> &[Frame]

Return an immutable reference to all image frames

§Returns

All frames in the image

Source

pub fn frames_mut(&mut self) -> &mut [Frame]

Return a mutable reference to all image frames.

Source

pub fn channels_ref(&self, ignore_alpha: bool) -> Vec<&Channel>

Return a reference to the underlying channels

Source

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

Source

pub const fn colorspace(&self) -> ColorSpace

Get the colorspace this image is stored in

Source

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

Source

pub fn flatten_to_u8(&self) -> Vec<Vec<u8>>

Convert the images to

Source

pub fn set_dimensions(&mut self, width: usize, height: usize)

Set new image dimensions

§Warning

This is potentially dangerous and should be used only when the underlying channels have been modified.

§Arguments:
  • width: The new image width
  • height: The new imag height.

Modifies the image in place

Source

pub fn fill<T>( pixel: T, colorspace: ColorSpace, width: usize, height: usize, ) -> Image
where T: Copy + Clone + 'static + ZuneInts<T> + Zeroable + Pod,

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);
Source

pub fn from_fn<T, F>( width: usize, height: usize, colorspace: ColorSpace, func: F, ) -> Image
where F: Fn(usize, usize, &mut [T; 4]), T: ZuneInts<T> + Copy + Clone + 'static + Default + Debug + Zeroable + Pod,

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

Source

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 usize this indicates that the array cannot be indexed by usize,hence values are invalid

  • If the length of pixels doesn’t match the expected length

Source

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

Source

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

Source

pub fn frames_len(&self) -> usize

Source§

impl Image

Pixel manipulation methods

Source

pub fn modify_pixels_mut<T, F>(&mut self, func: F) -> Result<(), ChannelErrors>
where T: ZuneInts<T> + Default + Copy + 'static + Pod, F: Fn(usize, usize, [&mut T; 4]),

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 in
    • x: 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 returns MAX_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

Source

pub fn convert_color(&mut self, to: ColorSpace) -> Result<(), ImageErrors>

Convert an image from one colorspace to another

§Arguments
  • to: The colorspace to convert image into
Source

pub fn convert_depth(&mut self, to: BitDepth) -> Result<(), ImageErrors>

Convert an image from one depth to another

§Arguments
  • to: The bit-depth to convert the image into

Trait Implementations§

Source§

impl Add for Image

Source§

type Output = Image

The resulting type after applying the + operator.
Source§

fn add(self, rhs: Image) -> Self::Output

Performs the + operation. Read more
Source§

impl Clone for Image

Source§

fn clone(&self) -> Image

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 Eq for Image

Source§

impl PartialEq for Image

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Sub for Image

Source§

type Output = Image

The resulting type after applying the - operator.
Source§

fn sub(self, rhs: Image) -> Self::Output

Performs the - operation. Read more

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> 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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> 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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more