Struct ImageBuffer
struct ImageBuffer<P: Pixel, Container> { ... }
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 ;
let mut img = new;
for x in 15..=17
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: Self, palette: &[(u8, u8, u8)], transparent_idx: Option<u8>) -> RgbaImageExpands 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<P> ImageBuffer<P, Vec<<P as >::Subpixel>>
fn from_par_fn<F>(width: u32, height: u32, f: F) -> ImageBuffer<P, Vec<<P as >::Subpixel>> where F: Fn(u32, u32) -> P + Send + SyncConstructs a new
ImageBufferby repeated application of the supplied function, utilizing multi-threading viarayon.The arguments to the function are the pixel's x and y coordinates.
Panics
Panics when the resulting image is larger the the maximum size of a vector.
impl<P, Container> ImageBuffer<P, Container>
fn pixels_mut(self: &mut Self) -> PixelsMut<'_, P>Returns an iterator over the mutable pixels of this image.
fn rows_mut(self: &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
0or a pixel type without any channels is used. This ensures that its length can always be represented byusize.fn enumerate_pixels_mut(self: &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(self: &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(self: &mut Self, x: u32, y: u32) -> &mut PGets 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(self: &mut Self, x: u32, y: u32) -> Option<&mut P>Gets a reference to the mutable pixel at location
(x, y)or returnsNoneif the index is out of the bounds(width, height).fn put_pixel(self: &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>
fn save_with_format<Q>(self: &Self, path: Q, format: ImageFormat) -> ImageResult<()> where Q: AsRef<Path>, P: PixelWithColorTypeSaves the buffer to a file at the specified path in the specified format.
See
save_buffer_with_formatfor supported types.
impl<P, Container> ImageBuffer<P, Container>
fn from_raw(width: u32, height: u32, buf: Container) -> Option<ImageBuffer<P, Container>>Constructs a buffer from a generic container (for example a
Vecor a slice)Returns
Noneif 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: Self) -> ContainerReturns the underlying raw buffer
fn as_raw(self: &Self) -> &ContainerReturns the underlying raw buffer
fn dimensions(self: &Self) -> (u32, u32)The width and height of this image.
fn width(self: &Self) -> u32The width of this image.
fn height(self: &Self) -> u32The height of this image.
fn pixels(self: &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: &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
0or a pixel type without any channels is used. This ensures that its length can always be represented byusize.fn enumerate_pixels(self: &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: &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: &Self, x: u32, y: u32) -> &PGets 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: &Self, x: u32, y: u32) -> Option<&P>Gets a reference to the pixel at location
(x, y)or returnsNoneif the index is out of the bounds(width, height).fn sample_layout(self: &Self) -> SampleLayoutGet the format of the buffer when viewed as a matrix of samples.
fn into_flat_samples(self: Self) -> FlatSamples<Container> where Container: AsRef<[<P as >::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 mostlyu8in which case the strides are also byte strides.fn as_flat_samples(self: &Self) -> FlatSamples<&[<P as >::Subpixel]> where Container: AsRef<[<P as >::Subpixel]>Return a view on the raw sample buffer.
See
into_flat_samplesfor more details.fn as_flat_samples_mut(self: &mut Self) -> FlatSamples<&mut [<P as >::Subpixel]> where Container: AsMut<[<P as >::Subpixel]>Return a mutable view on the raw sample buffer.
See
into_flat_samplesfor more details.
impl<P, Container> ImageBuffer<P, Container>
fn save<Q>(self: &Self, path: Q) -> ImageResult<()> where Q: AsRef<Path>, P: PixelWithColorTypeSaves the buffer to a file at the path specified.
The image format is derived from the file extension.
impl<P, Container> ImageBuffer<P, Container>
fn write_to<W>(self: &Self, writer: &mut W, format: ImageFormat) -> ImageResult<()> where W: Write + Seek, P: PixelWithColorTypeWrites the buffer to a writer in the specified format.
Assumes the writer is buffered. In most cases, you should wrap your writer in a
BufWriterfor best performance.
impl<P, Container> ImageBuffer<P, Container>
fn write_with_encoder<E>(self: &Self, encoder: E) -> ImageResult<()> where E: ImageEncoder, P: PixelWithColorTypeWrites the buffer with the given encoder.
impl<P, Container> ImageBuffer<P, Container>
fn par_pixels(self: &Self) -> PixelsPar<'_, P>Returns a parallel iterator over the pixels of this image, usable with
rayon. Seepixelsfor more information.fn par_enumerate_pixels(self: &Self) -> EnumeratePixelsPar<'_, P>Returns a parallel iterator over the pixels of this image and their coordinates, usable with
rayon. Seeenumerate_pixelsfor more information.
impl<P, Container> ImageBuffer<P, Container>
fn par_pixels_mut(self: &mut Self) -> PixelsMutPar<'_, P>Returns a parallel iterator over the mutable pixels of this image, usable with
rayon. Seepixels_mutfor more information.fn par_enumerate_pixels_mut(self: &mut Self) -> EnumeratePixelsMutPar<'_, P>Returns a parallel iterator over the mutable pixels of this image and their coordinates, usable with
rayon. Seeenumerate_pixels_mutfor more information.
impl<P: Pixel> ImageBuffer<P, Vec<<P as >::Subpixel>>
fn new(width: u32, height: u32) -> ImageBuffer<P, Vec<<P as >::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.
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 as >::Subpixel>>Constructs a new
ImageBufferby copying a pixelPanics
Panics when the resulting image is larger the the maximum size of a vector.
fn from_fn<F>(width: u32, height: u32, f: F) -> ImageBuffer<P, Vec<<P as >::Subpixel>> where F: FnMut(u32, u32) -> PConstructs a new
ImageBufferby 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 the the maximum size of a vector.
fn from_vec(width: u32, height: u32, buf: Vec<<P as >::Subpixel>) -> Option<ImageBuffer<P, Vec<<P as >::Subpixel>>>Creates an image buffer out of an existing buffer. Returns None if the buffer is not big enough.
fn into_vec(self: Self) -> Vec<<P as >::Subpixel>Consumes the image buffer and returns the underlying data as an owned buffer
impl From for ImageBuffer<Luma<u16>, Vec<u16>>
fn from(value: DynamicImage) -> Self
impl From for ImageBuffer<LumaA<u16>, Vec<u16>>
fn from(value: DynamicImage) -> Self
impl From for ImageBuffer<Rgb<u16>, Vec<u16>>
fn from(value: DynamicImage) -> Self
impl From for ImageBuffer<Rgba<u16>, Vec<u16>>
fn from(value: DynamicImage) -> Self
impl<Container, FromType: Pixel, ToType> ConvertBuffer for ImageBuffer<FromType, Container>
fn convert(self: &Self) -> ImageBuffer<ToType, Vec<<ToType as >::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>
fn clone(self: &Self) -> ImageBuffer<P, Container>fn clone_from(self: &mut Self, source: &Self)
impl<P, Container> Default for ImageBuffer<P, Container>
fn default() -> Self
impl<P, Container> Deref for ImageBuffer<P, Container>
fn deref(self: &Self) -> &<Self as Deref>::Target
impl<P, Container> DerefMut for ImageBuffer<P, Container>
fn deref_mut(self: &mut Self) -> &mut <Self as Deref>::Target
impl<P, Container> Freeze for ImageBuffer<P, Container>
impl<P, Container> GenericImage for ImageBuffer<P, Container>
fn get_pixel_mut(self: &mut Self, x: u32, y: u32) -> &mut Pfn put_pixel(self: &mut Self, x: u32, y: u32, pixel: P)unsafe fn unsafe_put_pixel(self: &mut Self, x: u32, y: u32, pixel: P)Puts a pixel at location (x, y), ignoring bounds checking.
fn blend_pixel(self: &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_within(self: &mut Self, source: Rect, x: u32, y: u32) -> bool
impl<P, Container> GenericImageView for ImageBuffer<P, Container>
fn dimensions(self: &Self) -> (u32, u32)fn get_pixel(self: &Self, x: u32, y: u32) -> Punsafe fn unsafe_get_pixel(self: &Self, x: u32, y: u32) -> PReturns the pixel located at (x, y), ignoring bounds checking.
impl<P, Container> Index for ImageBuffer<P, Container>
fn index(self: &Self, (x, y): (u32, u32)) -> &P
impl<P, Container> IndexMut for ImageBuffer<P, Container>
fn index_mut(self: &mut Self, (x, y): (u32, u32)) -> &mut P
impl<P, Container> RefUnwindSafe for ImageBuffer<P, Container>
impl<P, Container> Send for ImageBuffer<P, Container>
impl<P, Container> Sync for ImageBuffer<P, Container>
impl<P, Container> Unpin for ImageBuffer<P, Container>
impl<P, Container> UnsafeUnpin for ImageBuffer<P, Container>
impl<P, Container> UnwindSafe for ImageBuffer<P, Container>
impl<P, T> Receiver for ImageBuffer<P, Container>
impl<P: $crate::cmp::Eq + Pixel, Container: $crate::cmp::Eq> Eq for ImageBuffer<P, Container>
impl<P: $crate::cmp::PartialEq + Pixel, Container: $crate::cmp::PartialEq> PartialEq for ImageBuffer<P, Container>
fn eq(self: &Self, other: &ImageBuffer<P, Container>) -> bool
impl<P: $crate::fmt::Debug + Pixel, Container: $crate::fmt::Debug> Debug for ImageBuffer<P, Container>
fn fmt(self: &Self, f: &mut Formatter<'_>) -> Result
impl<P: $crate::hash::Hash + Pixel, Container: $crate::hash::Hash> Hash for ImageBuffer<P, Container>
fn hash<__H: $crate::hash::Hasher>(self: &Self, state: &mut __H)
impl<P: Pixel, Container> StructuralPartialEq for ImageBuffer<P, Container>
impl<R, P> ReadPrimitive for ImageBuffer<P, Container>
impl<T> Any for ImageBuffer<P, Container>
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for ImageBuffer<P, Container>
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for ImageBuffer<P, Container>
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> CloneToUninit for ImageBuffer<P, Container>
unsafe fn clone_to_uninit(self: &Self, dest: *mut u8)
impl<T> From for ImageBuffer<P, Container>
fn from(t: T) -> TReturns the argument unchanged.
impl<T> Pointable for ImageBuffer<P, Container>
unsafe fn init(init: <T as Pointable>::Init) -> usizeunsafe fn deref<'a>(ptr: usize) -> &'a Tunsafe fn deref_mut<'a>(ptr: usize) -> &'a mut Tunsafe fn drop(ptr: usize)
impl<T> ToOwned for ImageBuffer<P, Container>
fn to_owned(self: &Self) -> Tfn clone_into(self: &Self, target: &mut T)
impl<T, U> Into for ImageBuffer<P, Container>
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for ImageBuffer<P, Container>
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for ImageBuffer<P, Container>
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>