Struct ImageBuffer

pub struct ImageBuffer<P: Pixel, Container> { /* private fields */ }

Generic image buffer

This is an image parameterised by its Pixel types, represented by a width and height and a container of channel data. It provides direct access to its pixels and implements the GenericImageView and GenericImage traits. In many ways, this is the standard buffer implementing those traits. Using this concrete type instead of a generic type parameter has been shown to improve performance.

The crate defines a few type aliases with regularly used pixel types for your convenience, such as RgbImage, GrayImage etc.

To convert between images of different Pixel types use DynamicImage.

You can retrieve a complete description of the buffer's layout and contents through as_flat_samples and as_flat_samples_mut. This can be handy to also use the contents in a foreign language, map it as a GPU host buffer or other similar tasks.

Examples

Create a simple canvas and paint a small cross.

use image::{RgbImage, Rgb};

let mut img = RgbImage::new(32, 32);

for x in 15..=17 {
    for y in 8..24 {
        img.put_pixel(x, y, Rgb([255, 0, 0]));
        img.put_pixel(y, x, Rgb([255, 0, 0]));
    }
}

Overlays an image on top of a larger background raster.

use image::{GenericImage, GenericImageView, ImageBuffer, open};

let on_top = open("path/to/some.png").unwrap().into_rgb8();
let mut img = ImageBuffer::from_fn(512, 512, |x, y| {
    if (x + y) % 2 == 0 {
        image::Rgb([0, 0, 0])
    } else {
        image::Rgb([255, 255, 255])
    }
});

image::imageops::overlay(&mut img, &on_top, 128, 128);

Convert an RgbaImage to a GrayImage.

use image::{open, DynamicImage};

let rgba = open("path/to/some.png").unwrap().into_rgba8();
let gray = DynamicImage::ImageRgba8(rgba).into_luma8();

Implementations

impl ImageBuffer<Luma<u8>, Vec<u8>>

fn expand_palette(self, palette: &[(u8, u8, u8)], transparent_idx: Option<u8>) -> RgbaImage

Expands a color palette by re-using the existing buffer. Assumes 8 bit per pixel. Uses an optionally transparent index to adjust it's alpha value accordingly.

impl<C, SelfPixel> ImageBuffer<SelfPixel, C> where SelfPixel: PixelWithColorType + Pixel, C: Deref<Target = [SelfPixel::Subpixel]> + DerefMut,

fn copy_from_color_space<FromType, D>(&mut self, from: &ImageBuffer<FromType, D>, options: ConvertColorOptions) -> ImageResult<()>
where
    FromType: Pixel<Subpixel = SelfPixel::Subpixel> + PixelWithColorType,
    D: Deref<Target = [SelfPixel::Subpixel]>,

Copy pixel data from one buffer to another, calculating equivalent color representations for the target's color space.

Returns Ok if:

  • Both images to have the same dimensions, otherwise returns a ImageError::Parameter.
  • The primaries and transfer functions of both image's color spaces must be supported, otherwise returns a ImageError::Unsupported.
  • The pixel's channel layout must be supported for conversion, otherwise returns a ImageError::Unsupported. You can rely on RGB and RGBA always being supported. If a layout is supported for one color space it is supported for all of them.

To copy color data of arbitrary channel layouts use DynamicImage with the overhead of having data converted into and from RGB representation.

fn to_color_space<IntoType>(&self, color: Cicp, options: ConvertColorOptions) -> Result<ImageBuffer<IntoType, Vec<SelfPixel::Subpixel>>, ImageError>
where
    IntoType: Pixel<Subpixel = SelfPixel::Subpixel> + PixelWithColorType,

Convert this buffer into a newly allocated buffer, changing the color representation.

This will avoid an allocation if the target layout or the color conversion is not supported (yet).

See ImageBuffer::copy_from_color_space if you intend to assign to an existing buffer, swapping the argument with self.

fn apply_color_space(&mut self, color: Cicp, options: ConvertColorOptions) -> ImageResult<()>

Apply a color space to an image, transforming the pixel representation.

impl<P> ImageBuffer<P, Vec<P::Subpixel>> where P: Pixel + Send + Sync, P::Subpixel: Send + Sync,

fn from_par_fn<F>(width: u32, height: u32, f: F) -> ImageBuffer<P, Vec<P::Subpixel>>
where
    F: Fn(u32, u32) -> P + Send + Sync,

Constructs a new ImageBuffer by repeated application of the supplied function, utilizing multi-threading via rayon.

The arguments to the function are the pixel's x and y coordinates.

Panics

Panics when the resulting image is larger than the maximum size of a vector.

impl<P, Container> ImageBuffer<P, Container> where P: Pixel + Send + Sync, P::Subpixel: Send + Sync, Container: Deref<Target = [P::Subpixel]> + DerefMut,

fn par_pixels_mut(&mut self) -> PixelsMutPar<'_, P>

Returns a parallel iterator over the mutable pixels of this image, usable with rayon. See pixels_mut for more information.

fn par_enumerate_pixels_mut(&mut self) -> EnumeratePixelsMutPar<'_, P>

Returns a parallel iterator over the mutable pixels of this image and their coordinates, usable with rayon. See enumerate_pixels_mut for more information.

impl<P, Container> ImageBuffer<P, Container> where P: Pixel + Sync, P::Subpixel: Sync, Container: Deref<Target = [P::Subpixel]>,

fn par_pixels(&self) -> PixelsPar<'_, P>

Returns a parallel iterator over the pixels of this image, usable with rayon. See pixels for more information.

fn par_enumerate_pixels(&self) -> EnumeratePixelsPar<'_, P>

Returns a parallel iterator over the pixels of this image and their coordinates, usable with rayon. See enumerate_pixels for more information.

impl<P, Container> ImageBuffer<P, Container> where P: Pixel, Container: Deref<Target = [P::Subpixel]> + DerefMut,

fn pixels_mut(&mut self) -> PixelsMut<'_, P>

Returns an iterator over the mutable pixels of this image.

fn rows_mut(&mut self) -> RowsMut<'_, P>

Returns an iterator over the mutable rows of this image.

Only non-empty rows can be iterated in this manner. In particular the iterator will not yield any item when the width of the image is 0 or a pixel type without any channels is used. This ensures that its length can always be represented by usize.

fn enumerate_pixels_mut(&mut self) -> EnumeratePixelsMut<'_, P>

Enumerates over the pixels of the image. The iterator yields the coordinates of each pixel along with a mutable reference to them.

fn enumerate_rows_mut(&mut self) -> EnumerateRowsMut<'_, P>

Enumerates over the rows of the image. The iterator yields the y-coordinate of each row along with a mutable reference to them.

fn get_pixel_mut(&mut self, x: u32, y: u32) -> &mut P

Gets a reference to the mutable pixel at location (x, y)

Panics

Panics if (x, y) is out of the bounds (width, height).

fn get_pixel_mut_checked(&mut self, x: u32, y: u32) -> Option<&mut P>

Gets a reference to the mutable pixel at location (x, y) or returns None if the index is out of the bounds (width, height).

fn put_pixel(&mut self, x: u32, y: u32, pixel: P)

Puts a pixel at location (x, y)

Panics

Panics if (x, y) is out of the bounds (width, height).

impl<P, Container> ImageBuffer<P, Container> where P: Pixel, Container: Deref<Target = [P::Subpixel]>,

fn from_raw(width: u32, height: u32, buf: Container) -> Option<ImageBuffer<P, Container>>

Constructs a buffer from a generic container (for example a Vec or a slice)

Returns None if the container is not big enough (including when the image dimensions necessitate an allocation of more bytes than supported by the container).

fn into_raw(self) -> Container

Returns the underlying raw buffer

fn as_raw(&self) -> &Container

Returns the underlying raw buffer

fn dimensions(&self) -> (u32, u32)

The width and height of this image.

fn width(&self) -> u32

The width of this image.

fn height(&self) -> u32

The height of this image.

fn pixels(&self) -> Pixels<'_, P>

Returns an iterator over the pixels of this image. The iteration order is x = 0 to width then y = 0 to height

fn rows(&self) -> Rows<'_, P>

Returns an iterator over the rows of this image.

Only non-empty rows can be iterated in this manner. In particular the iterator will not yield any item when the width of the image is 0 or a pixel type without any channels is used. This ensures that its length can always be represented by usize.

fn enumerate_pixels(&self) -> EnumeratePixels<'_, P>

Enumerates over the pixels of the image. The iterator yields the coordinates of each pixel along with a reference to them. The iteration order is x = 0 to width then y = 0 to height Starting from the top left.

fn enumerate_rows(&self) -> EnumerateRows<'_, P>

Enumerates over the rows of the image. The iterator yields the y-coordinate of each row along with a reference to them.

fn get_pixel(&self, x: u32, y: u32) -> &P

Gets a reference to the pixel at location (x, y)

Panics

Panics if (x, y) is out of the bounds (width, height).

fn get_pixel_checked(&self, x: u32, y: u32) -> Option<&P>

Gets a reference to the pixel at location (x, y) or returns None if the index is out of the bounds (width, height).

fn sample_layout(&self) -> SampleLayout

Get the format of the buffer when viewed as a matrix of samples.

fn into_flat_samples(self) -> FlatSamples<Container>
where
    Container: AsRef<[P::Subpixel]>,

Return the raw sample buffer with its stride an dimension information.

The returned buffer is guaranteed to be well formed in all cases. It is laid out by colors, width then height, meaning channel_stride <= width_stride <= height_stride. All strides are in numbers of elements but those are mostly u8 in which case the strides are also byte strides.

fn as_flat_samples(&self) -> FlatSamples<&[P::Subpixel]>

Return a view on the raw sample buffer.

See into_flat_samples for more details.

fn as_flat_samples_mut(&mut self) -> FlatSamples<&mut [P::Subpixel]>
where
    Container: AsMut<[P::Subpixel]>,

Return a mutable view on the raw sample buffer.

See into_flat_samples for more details.

impl<P, Container> ImageBuffer<P, Container> where P: Pixel, [P::Subpixel]: EncodableLayout, Container: Deref<Target = [P::Subpixel]>,

fn save<Q>(&self, path: Q) -> ImageResult<()>
where
    Q: AsRef<Path>,
    P: PixelWithColorType,

Saves the buffer to a file at the path specified.

The image format is derived from the file extension.

impl<P, Container> ImageBuffer<P, Container> where P: Pixel, [P::Subpixel]: EncodableLayout, Container: Deref<Target = [P::Subpixel]>,

fn save_with_format<Q>(&self, path: Q, format: ImageFormat) -> ImageResult<()>
where
    Q: AsRef<Path>,
    P: PixelWithColorType,

Saves the buffer to a file at the specified path in the specified format.

See save_buffer_with_format for supported types.

impl<P, Container> ImageBuffer<P, Container> where P: Pixel, [P::Subpixel]: EncodableLayout, Container: Deref<Target = [P::Subpixel]>,

fn write_to<W>(&self, writer: &mut W, format: ImageFormat) -> ImageResult<()>
where
    W: Write + Seek,
    P: PixelWithColorType,

Writes the buffer to a writer in the specified format.

Assumes the writer is buffered. In most cases, you should wrap your writer in a BufWriter for best performance.

impl<P, Container> ImageBuffer<P, Container> where P: Pixel, [P::Subpixel]: EncodableLayout, Container: Deref<Target = [P::Subpixel]>,

fn write_with_encoder<E>(&self, encoder: E) -> ImageResult<()>
where
    E: ImageEncoder,
    P: PixelWithColorType,

Writes the buffer with the given encoder.

impl<P: Pixel> ImageBuffer<P, Vec<P::Subpixel>>

fn new(width: u32, height: u32) -> ImageBuffer<P, Vec<P::Subpixel>>

Creates a new image buffer based on a Vec<P::Subpixel>.

all the pixels of this image have a value of zero, regardless of the data type or number of channels.

The color space is initially set to [sRGB]Cicp::SRGB.

Panics

Panics when the resulting image is larger than the maximum size of a vector.

fn from_pixel(width: u32, height: u32, pixel: P) -> ImageBuffer<P, Vec<P::Subpixel>>

Constructs a new ImageBuffer by copying a pixel

Panics

Panics when the resulting image is larger than the maximum size of a vector.

fn from_fn<F>(width: u32, height: u32, f: F) -> ImageBuffer<P, Vec<P::Subpixel>>
where
    F: FnMut(u32, u32) -> P,

Constructs a new ImageBuffer by repeated application of the supplied function.

The arguments to the function are the pixel's x and y coordinates.

Panics

Panics when the resulting image is larger than the maximum size of a vector.

fn from_vec(width: u32, height: u32, buf: Vec<P::Subpixel>) -> Option<ImageBuffer<P, Vec<P::Subpixel>>>

Creates an image buffer out of an existing buffer. Returns None if the buffer is not big enough.

fn into_vec(self) -> Vec<P::Subpixel>

Consumes the image buffer and returns the underlying data as an owned buffer

impl<P: Pixel, Container> ImageBuffer<P, Container>

fn set_rgb_primaries(&mut self, color: CicpColorPrimaries)

Define the color space for the image.

The color data is unchanged. Reinterprets the existing red, blue, green channels as points in the new set of primary colors, changing the apparent shade of pixels.

Note that the primaries also define a reference whitepoint When this buffer contains Luma data, the luminance channel is interpreted as the Y channel of a related YCbCr color space as if by a non-constant chromaticity derived matrix. That is, coefficients are not applied in the linear RGB space but use encoded channel values. (In a color space with the linear transfer function there is no difference).

The default color space is Cicp::SRGB.

fn set_transfer_function(&mut self, tf: CicpTransferCharacteristics)

Define the transfer function for the image.

The color data is unchanged. Reinterprets all (non-alpha) components in the image, potentially changing the apparent shade of pixels. Individual components are always interpreted as encoded numbers. To denote numbers in a linear RGB space, use CicpTransferCharacteristics::Linear.

The default color space is Cicp::SRGB.

fn color_space(&self) -> Cicp

Get the Cicp encoding of this buffer's color data.

fn set_color_space(&mut self, cicp: Cicp) -> ImageResult<()>

Set primaries and transfer characteristics from a Cicp color space.

Returns an error if cicp uses features that are not support with an RGB color space, e.g. a matrix or narrow range (studio encoding) channels.

impl<S, Container> ImageBuffer<Rgb<S>, Container> where Rgb<S>: PixelWithColorType<Subpixel = S>, Container: DerefMut<Target = [S]>,

fn from_raw_bgr(width: u32, height: u32, container: Container) -> Option<Self>

Construct an image by swapping Bgr channels into an Rgb order.

fn into_raw_bgr(self) -> Container

Return the underlying raw buffer after converting it into Bgr channel order.

impl<S, Container> ImageBuffer<Rgba<S>, Container> where Rgba<S>: PixelWithColorType<Subpixel = S>, Container: DerefMut<Target = [S]>,

fn from_raw_bgra(width: u32, height: u32, container: Container) -> Option<Self>

Construct an image by swapping BgrA channels into an RgbA order.

fn into_raw_bgra(self) -> Container

Return the underlying raw buffer after converting it into BgrA channel order.

Trait Implementations

impl From<DynamicImage> for ImageBuffer<Luma<u16>, Vec<u16>>

fn from(value: DynamicImage) -> Self

impl From<DynamicImage> for ImageBuffer<LumaA<u16>, Vec<u16>>

fn from(value: DynamicImage) -> Self

impl From<DynamicImage> for ImageBuffer<Rgb<u16>, Vec<u16>>

fn from(value: DynamicImage) -> Self

impl From<DynamicImage> for ImageBuffer<Rgba<u16>, Vec<u16>>

fn from(value: DynamicImage) -> Self

impl<Container, FromType: Pixel, ToType> ConvertBuffer<ImageBuffer<ToType, Vec<<ToType as Pixel>::Subpixel>>> for ImageBuffer<FromType, Container> where Container: Deref<Target = [FromType::Subpixel]>, ToType: FromColor<FromType> + Pixel,

fn convert(&self) -> ImageBuffer<ToType, Vec<ToType::Subpixel>>

Examples

Convert RGB image to gray image.

use image::buffer::ConvertBuffer;
use image::GrayImage;

let image_path = "examples/fractal.png";
let image = image::open(&image_path)
    .expect("Open file failed")
    .to_rgba8();

let gray_image: GrayImage = image.convert();

impl<P, Container> Clone for ImageBuffer<P, Container> where P: Pixel, Container: Deref<Target = [P::Subpixel]> + Clone,

fn clone(&self) -> ImageBuffer<P, Container>
fn clone_from(&mut self, source: &Self)

impl<P, Container> Default for ImageBuffer<P, Container> where P: Pixel, Container: Default,

fn default() -> Self

impl<P, Container> Deref for ImageBuffer<P, Container> where P: Pixel, Container: Deref<Target = [P::Subpixel]>,

type Target = [<P as Pixel>::Subpixel];
fn deref(&self) -> &<Self as Deref>::Target

impl<P, Container> DerefMut for ImageBuffer<P, Container> where P: Pixel, Container: Deref<Target = [P::Subpixel]> + DerefMut,

fn deref_mut(&mut self) -> &mut <Self as Deref>::Target

impl<P, Container> GenericImage for ImageBuffer<P, Container> where P: Pixel, Container: Deref<Target = [P::Subpixel]> + DerefMut,

fn get_pixel_mut(&mut self, x: u32, y: u32) -> &mut P
fn put_pixel(&mut self, x: u32, y: u32, pixel: P)
unsafe fn unsafe_put_pixel(&mut self, x: u32, y: u32, pixel: P)

Puts a pixel at location (x, y), ignoring bounds checking.

fn blend_pixel(&mut self, x: u32, y: u32, p: P)

Put a pixel at location (x, y), taking into account alpha channels

DEPRECATED: This method will be removed. Blend the pixel directly instead.

fn copy_from_samples(&mut self, view: ViewOfPixel<'_, Self::Pixel>, x: u32, y: u32) -> ImageResult<()>
fn copy_within(&mut self, source: Rect, x: u32, y: u32) -> bool

impl<P, Container> GenericImageView for ImageBuffer<P, Container> where P: Pixel, Container: Deref<Target = [P::Subpixel]> + Deref,

type Pixel = P;
fn dimensions(&self) -> (u32, u32)
fn get_pixel(&self, x: u32, y: u32) -> P
fn to_pixel_view(&self) -> Option<ViewOfPixel<'_, Self::Pixel>>
unsafe fn unsafe_get_pixel(&self, x: u32, y: u32) -> P

Returns the pixel located at (x, y), ignoring bounds checking.

fn buffer_with_dimensions(&self, width: u32, height: u32) -> ImageBuffer<P, Vec<P::Subpixel>>

impl<P, Container> Index<(u32, u32)> for ImageBuffer<P, Container> where P: Pixel, Container: Deref<Target = [P::Subpixel]>,

type Output = P;
fn index(&self, (x, y): (u32, u32)) -> &P

impl<P, Container> IndexMut<(u32, u32)> for ImageBuffer<P, Container> where P: Pixel, Container: Deref<Target = [P::Subpixel]> + DerefMut,

fn index_mut(&mut self, (x, y): (u32, u32)) -> &mut P

impl<P: Debug + Pixel, Container: Debug> Debug for ImageBuffer<P, Container>

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

impl<P: Eq + Pixel, Container: Eq> Eq for ImageBuffer<P, Container>

impl<P: Hash + Pixel, Container: Hash> Hash for ImageBuffer<P, Container>

fn hash<__H: Hasher>(&self, state: &mut __H)

impl<P: PartialEq + Pixel, Container: PartialEq> PartialEq for ImageBuffer<P, Container>

fn eq(&self, other: &ImageBuffer<P, Container>) -> bool

impl<P: PartialEq + Pixel, Container: PartialEq> StructuralPartialEq for ImageBuffer<P, Container>

Auto Trait Implementations

impl<P, Container> Freeze for ImageBuffer<P, Container> where PhantomData<P>: Freeze, Container: Freeze,

impl<P, Container> RefUnwindSafe for ImageBuffer<P, Container> where PhantomData<P>: RefUnwindSafe, Container: RefUnwindSafe,

impl<P, Container> Send for ImageBuffer<P, Container> where PhantomData<P>: Send, Container: Send,

impl<P, Container> Sync for ImageBuffer<P, Container> where PhantomData<P>: Sync, Container: Sync,

impl<P, Container> Unpin for ImageBuffer<P, Container> where PhantomData<P>: Unpin, Container: Unpin,

impl<P, Container> UnsafeUnpin for ImageBuffer<P, Container> where PhantomData<P>: UnsafeUnpin, Container: UnsafeUnpin,

impl<P, Container> UnwindSafe for ImageBuffer<P, Container> where PhantomData<P>: UnwindSafe, Container: UnwindSafe,

Blanket Implementations

impl<P, T> Receiver for ImageBuffer<P, Container> where P: Deref<Target = T> + ?Sized, T: ?Sized,

type Target = T;

impl<R, P> ReadPrimitive<R> for ImageBuffer<P, Container> where R: Read + ReadEndian<P>, P: Default,

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for ImageBuffer<P, Container> where ST: ?Sized, DT: ?Sized,

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for ImageBuffer<P, Container> where ST: ?Sized, DT: ?Sized,

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

fn type_id(&self) -> TypeId

impl<T> Borrow<T> for ImageBuffer<P, Container> where T: ?Sized,

fn borrow(&self) -> &T

impl<T> BorrowMut<T> for ImageBuffer<P, Container> where T: ?Sized,

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

impl<T> CloneToUninit for ImageBuffer<P, Container> where T: Clone,

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

impl<T> From<T> for ImageBuffer<P, Container>

fn from(t: T) -> T

Returns the argument unchanged.

impl<T> IntoEither for ImageBuffer<P, Container>

impl<T> Pointable for ImageBuffer<P, Container>

const ALIGN: usize = _;
type Init = T;
unsafe fn init(init: <T as Pointable>::Init) -> usize
unsafe fn deref<'a>(ptr: usize) -> &'a T
unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T
unsafe fn drop(ptr: usize)

impl<T> Read<Exclusive, BecauseExclusive> for ImageBuffer<P, Container> where T: ?Sized,

impl<T> ToOwned for ImageBuffer<P, Container> where T: Clone,

type Owned = T;
fn to_owned(&self) -> T
fn clone_into(&self, target: &mut T)

impl<T, U> Into<U> for ImageBuffer<P, Container> where U: From<T>,

fn into(self) -> U

Calls U::from(self).

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

impl<T, U> TryFrom<U> for ImageBuffer<P, Container> where U: Into<T>,

type Error = never;
fn try_from(value: U) -> Result<T, never>

impl<T, U> TryInto<U> for ImageBuffer<P, Container> where U: TryFrom<T>,

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