### Example: Accessing and Modifying Samples Source: https://docs.rs/image/latest/src/image/images/flat.rs.html?search=u32+-%3E+bool Demonstrates how to safely get and modify individual samples within a FlatSamples buffer. It shows how to access a specific channel's sample at given coordinates and handle cases where a channel might not exist. ```rust # use image::{RgbImage}; let mut flat = RgbImage::new(480, 640).into_flat_samples(); // Assign some new color to the blue channel at (10, 10). *flat.get_mut_sample(1, 10, 10).unwrap() = 255; // There is no alpha channel. assert!(flat.get_mut_sample(3, 10, 10).is_none()); ``` -------------------------------- ### Basic SIMD Summation Example Source: https://docs.rs/image/latest/image/struct.ImageBuffer.html Demonstrates a basic summation of floating-point numbers using SIMD operations. This example requires a compatible SIMD implementation. ```rust let numbers: Vec = (1..101).map(|x| x as _).collect(); assert_eq!(basic_simd_sum(&numbers[1..99]), 4949.0); ``` -------------------------------- ### Sample Encoding Search Examples Source: https://docs.rs/image/latest/image/codecs/pnm/enum.SampleEncoding.html?search= Examples of how to search for sample encodings. ```APIDOC ## Search Examples ### Example 1: Searching for a specific type ``` std::vec ``` ### Example 2: Searching for a type conversion ``` u32 -> bool ``` ### Example 3: Searching for a generic function with type parameters ``` Option, (T -> U) -> Option ``` ``` -------------------------------- ### Example Usage of horizontal_gradient Source: https://docs.rs/image/latest/image/imageops/fn.horizontal_gradient.html?search=u32+-%3E+bool An example demonstrating how to use the horizontal_gradient function to create a gradient image and save it. ```rust use image::{Rgba, RgbaImage, Pixel}; let mut img = RgbaImage::new(100, 100); let start = Rgba::from_slice(&[0, 128, 0, 0]); let end = Rgba::from_slice(&[255, 255, 255, 255]); image::imageops::horizontal_gradient(&mut img, start, end); img.save("horizontal_gradient.png").unwrap(); ``` -------------------------------- ### Basic Image Inspection Example Source: https://docs.rs/image/latest/src/image/images/generic_image.rs.html?search=std%3A%3Avec Demonstrates how to use the GenericImageView trait to get dimensions and pixel data from an image buffer. This is useful for reading image properties and accessing individual pixels. ```rust use image::{GenericImageView, Rgb, RgbImage}; let buffer = RgbImage::new(10, 10); let image: &dyn GenericImageView> = &buffer; ``` -------------------------------- ### Get element offset by reference Source: https://docs.rs/image/latest/struct.ImageBuffer.html Returns the index of an element reference within the slice. Returns `None` if the element reference does not point to the start of an element. This method uses pointer arithmetic and does not compare elements. ```rust let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` ```rust let arr: &[[u32; 2]] = &[[0, 1], [2, 3]]; let flat_arr: &[u32] = arr.as_flattened(); let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap(); let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap(); assert_eq!(ok_elm, &[0, 1]); assert_eq!(weird_elm, &[1, 2]); assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0 assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1 ``` -------------------------------- ### ImageBuffer::sample_layout Source: https://docs.rs/image/latest/image/type.GrayAlphaImage.html?search=std%3A%3Avec Gets the sample layout of the buffer. ```APIDOC ## ImageBuffer::sample_layout ### Description Get the format of the buffer when viewed as a matrix of samples. ### Method `sample_layout(&self) -> SampleLayout` ### Returns - `SampleLayout` - The sample layout of the buffer. ``` -------------------------------- ### Shift Right Example Source: https://docs.rs/image/latest/struct.ImageBuffer.html Demonstrates shifting elements to the right and inserting new elements at the beginning. This is useful for managing fixed-size buffers where elements are added and removed from the front. ```rust #![feature(slice_shift)] // Same as the diagram above let mut a = [5, 6, 7, 8, 9]; let inserted = [0]; let returned = a.shift_right(inserted); assert_eq!(returned, [9]); assert_eq!(a, [0, 5, 6, 7, 8]); // The name comes from this operation's similarity to bitshifts let mut a: u8 = 0b10010110; a >>= 3; assert_eq!(a, 0b00010010_u8); let mut a: [_; 8] = [1, 0, 0, 1, 0, 1, 1, 0]; a.shift_right([0; 3]); assert_eq!(a, [0, 0, 0, 1, 0, 0, 1, 0]); // Remember you can sub-slice to affect less that the whole slice. // For example, this is similar to `.remove(4)` + `.insert(1, 'Z')` let mut a = ['a', 'b', 'c', 'd', 'e', 'f']; assert_eq!(a[1..=4].shift_right(['Z']), ['e']); assert_eq!(a, ['a', 'Z', 'b', 'c', 'd', 'f']); // If the size matches it's equivalent to `mem::replace` let mut a = [1, 2, 3]; assert_eq!(a.shift_right([7, 8, 9]), [1, 2, 3]); assert_eq!(a, [7, 8, 9]); // Some of the "inserted" elements end up returned if the slice is too short let mut a = []; assert_eq!(a.shift_right([1, 2, 3]), [1, 2, 3]); let mut a = [9]; assert_eq!(a.shift_right([1, 2, 3]), [2, 3, 9]); assert_eq!(a, [1]); ``` -------------------------------- ### Splitting Off Slice from Third Element Source: https://docs.rs/image/latest/image/struct.ImageBuffer.html?search=std%3A%3Avec Demonstrates using `split_off` to get a sub-slice starting from a specific index. ```rust let mut slice: &[_] = &['a', 'b', 'c', 'd']; let mut tail = slice.split_off(2..).unwrap(); assert_eq!(slice, &['a', 'b']); assert_eq!(tail, &['c', 'd']); ``` ```rust let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd']; let mut tail = slice.split_off_mut(2..).unwrap(); assert_eq!(slice, &mut ['a', 'b']); assert_eq!(tail, &mut ['c', 'd']); ``` -------------------------------- ### Example Usage of tile Function Source: https://docs.rs/image/latest/image/imageops/fn.tile.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to use the `tile` function to create a tiled wallpaper. It opens a tile image, tiles it onto a larger base image, and saves the result. ```rust use image::RgbaImage; let mut img = RgbaImage::new(1920, 1080); let tile = image::open("tile.png").unwrap(); image::imageops::tile(&mut img, &tile); img.save("tiled_wallpaper.png").unwrap(); ``` -------------------------------- ### Tiling an Image Source: https://docs.rs/image/latest/image/imageops/fn.tile.html This example demonstrates how to tile a smaller image (`tile.png`) onto a larger image (`img`). Ensure `tile.png` exists in the project directory. ```Rust use image::RgbaImage; let mut img = RgbaImage::new(1920, 1080); let tile = image::open("tile.png").unwrap(); image::imageops::tile(&mut img, &tile); img.save("tiled_wallpaper.png").unwrap(); ``` -------------------------------- ### Iterating Over Slice Items Source: https://docs.rs/image/latest/image/struct.ImageBuffer.html?search=std%3A%3Avec Use `iter()` to get an immutable iterator over slice elements. The iterator yields items from start to end. ```rust let x = &[1, 2, 4]; let mut iterator = x.iter(); assert_eq!(iterator.next(), Some(&1)); assert_eq!(iterator.next(), Some(&2)); assert_eq!(iterator.next(), Some(&4)); assert_eq!(iterator.next(), None); ``` -------------------------------- ### Get SubImage Offsets Source: https://docs.rs/image/latest/image/struct.SubImage.html Retrieves the current offsets (x, y) of the SubImage relative to its parent image. This indicates the starting position of the sub-region. ```rust pub fn offsets(&self) -> (u32, u32) ``` -------------------------------- ### Tile Image Example Source: https://docs.rs/image/latest/src/image/imageops/mod.rs.html?search=std%3A%3Avec Demonstrates how to tile an image by repeating a 'tile' image to fill a larger 'bottom' image. This is useful for creating wallpapers or repeating patterns. ```rust pub fn tile(bottom: &mut I, top: &J) where I: GenericImage, J: GenericImageView, { for x in (0..bottom.width()).step_by(top.width() as usize) { // The loop continues here to tile vertically as well. // For brevity, only the horizontal tiling part is shown in this snippet. } } ``` ```rust use image::RgbaImage; let mut img = RgbaImage::new(1920, 1080); let tile = image::open("tile.png").unwrap(); image::imageops::tile(&mut img, &tile); img.save("tiled_wallpaper.png").unwrap(); ``` -------------------------------- ### Get Channel Count for ColorType Source: https://docs.rs/image/latest/image/enum.ColorType.html?search=u32+-%3E+bool Returns the number of color channels that constitute a pixel for the given ColorType. For example, RGB has 3 channels, RGBA has 4. ```rust pub fn channel_count(self) -> u8 ``` -------------------------------- ### Example: Applying Orientation from Decoder Source: https://docs.rs/image/latest/src/image/images/dynimage.rs.html?search= Demonstrates how to read Exif orientation from an image file and apply it to a DynamicImage. ```rust # fn only_check_if_this_compiles() -> Result<(), Box> { use image::{DynamicImage, ImageReader, ImageDecoder}; let mut decoder = ImageReader::open("file.jpg")?.into_decoder()?; let orientation = decoder.orientation()?; let mut image = DynamicImage::from_decoder(decoder)?; image.apply_orientation(orientation); # Ok(()) # } ``` -------------------------------- ### Partition Point Example Source: https://docs.rs/image/latest/struct.ImageBuffer.html Finds the index where a slice can be partitioned based on a predicate. Useful for inserting elements while maintaining order. ```rust let mut v = [1, 2, 3, 4, 5, 6, 7, 8, 9]; let i = v.partition_point(|&x| x < 5); assert_eq!(i, 4); assert!(v[..i].iter().all(|&x| x < 5)); assert!(v[i..].iter().all(|&x| !(x < 5))); ``` ```rust let a = [2, 4, 8]; assert_eq!(a.partition_point(|x| x < &100), a.len()); let a: [i32; 0] = []; assert_eq!(a.partition_point(|x| x < &100), 0); ``` ```rust let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; let num = 42; let idx = s.partition_point(|&x| x <= num); s.insert(idx, num); assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]); ``` -------------------------------- ### Get Buffer Slice Source: https://docs.rs/image/latest/image/hooks/type.DecodingHook.html?search= Returns a slice of bytes starting from the current position. The length of the slice can be less than the remaining bytes, accommodating non-contiguous internal representations. ```rust fn chunk(&self) -> &[u8] ``` -------------------------------- ### init Source: https://docs.rs/image/latest/image/buffer/struct.EnumeratePixels.html Initializes a with the given initializer. ```APIDOC ## unsafe fn init(init: ::Init) -> usize ### Description Initializes a with the given initializer. ### Parameters #### Path Parameters - **init** (::Init) - Required - The initializer value. ``` -------------------------------- ### Initialize WebPDecoder Source: https://docs.rs/image/latest/src/image/codecs/webp/decoder.rs.html Creates a new `WebPDecoder` from a `BufRead` and `Seek` compatible reader. Handles potential WebP decoding errors. ```rust pub fn new(r: R) -> ImageResult { Ok(Self { inner: image_webp::WebPDecoder::new(r).map_err(ImageError::from_webp_decode)?, orientation: None, }) } ``` -------------------------------- ### ICO Decoder Initialization and Error Handling Source: https://docs.rs/image/latest/src/image/codecs/ico/decoder.rs.html Demonstrates initializing the ICO decoder with sample data and verifying that reading invalid image data results in an error. ```rust let data = [ 0x00, 0x00, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0x50, 0x37, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc7, 0x37, 0x61, ]; let decoder = IcoDecoder::new(std::io::Cursor::new(&data)).unwrap(); let mut buf = vec![0; usize::try_from(decoder.total_bytes()).unwrap()]; assert!(decoder.read_image(&mut buf).is_err()); ``` -------------------------------- ### Generate a horizontal gradient in an RgbaImage Source: https://docs.rs/image/latest/image/imageops/fn.horizontal_gradient.html This example demonstrates how to create a new RgbaImage and fill it with a horizontal gradient using the `horizontal_gradient` function. It defines start and end colors and saves the resulting image. ```Rust use image::{Rgba, RgbaImage, Pixel}; let mut img = RgbaImage::new(100, 100); let start = Rgba::from_slice(&[0, 128, 0, 0]); let end = Rgba::from_slice(&[255, 255, 255, 255]); image::imageops::horizontal_gradient(&mut img, start, end); img.save("horizontal_gradient.png").unwrap(); ``` -------------------------------- ### Shift Left Example Source: https://docs.rs/image/latest/struct.ImageBuffer.html Demonstrates shifting elements to the left and inserting new elements at the end. This is useful for managing fixed-size buffers where elements are added and removed cyclically. ```rust #![feature(slice_shift)] // Same as the diagram above let mut a = [1, 2, 3, 4, 5]; let inserted = [9]; let returned = a.shift_left(inserted); assert_eq!(returned, [1]); assert_eq!(a, [2, 3, 4, 5, 9]); // You can shift multiple items at a time let mut a = *b"Hello world"; assert_eq!(a.shift_left(*b" peace"), *b"Hello "); assert_eq!(a, *b"world peace"); // The name comes from this operation's similarity to bitshifts let mut a: u8 = 0b10010110; a <<= 3; assert_eq!(a, 0b10110000_u8); let mut a: [_; 8] = [1, 0, 0, 1, 0, 1, 1, 0]; a.shift_left([0; 3]); assert_eq!(a, [1, 0, 1, 1, 0, 0, 0, 0]); // Remember you can sub-slice to affect less that the whole slice. // For example, this is similar to `.remove(1)` + `.insert(4, 'Z')` let mut a = ['a', 'b', 'c', 'd', 'e', 'f']; assert_eq!(a[1..=4].shift_left(['Z']), ['b']); assert_eq!(a, ['a', 'c', 'd', 'e', 'Z', 'f']); // If the size matches it's equivalent to `mem::replace` let mut a = [1, 2, 3]; assert_eq!(a.shift_left([7, 8, 9]), [1, 2, 3]); assert_eq!(a, [7, 8, 9]); // Some of the "inserted" elements end up returned if the slice is too short let mut a = []; assert_eq!(a.shift_left([1, 2, 3]), [1, 2, 3]); let mut a = [9]; assert_eq!(a.shift_left([1, 2, 3]), [9, 1, 2]); assert_eq!(a, [3]); ``` -------------------------------- ### Chunking a slice based on a non-decreasing predicate Source: https://docs.rs/image/latest/struct.ImageBuffer.html This example demonstrates using `chunk_by` with a predicate that checks for non-decreasing order, effectively extracting sorted subslices. ```rust let slice = &[1, 1, 2, 3, 2, 3, 2, 3, 4]; let mut iter = slice.chunk_by(|a, b| a <= b); assert_eq!(iter.next(), Some(&[1, 1, 2, 3][..])); assert_eq!(iter.next(), Some(&[2, 3][..])); assert_eq!(iter.next(), Some(&[2, 3, 4][..])); assert_eq!(iter.next(), None); ``` -------------------------------- ### get Source: https://docs.rs/image/latest/struct.ImageBuffer.html Safely retrieves a reference to an element or subslice using an index. Returns `None` if the index is out of bounds. ```APIDOC ## pub fn get(&self, index: I) -> Option<&>::Output> ### Description Returns a reference to an element or subslice depending on the type of index. If given a position, returns a reference to the element at that position or `None` if out of bounds. If given a range, returns the subslice corresponding to that range, or `None` if out of bounds. ### Method `get` ### Parameters - `index`: An index of type `I` which implements `SliceIndex<[T]>`. This can be a single index (e.g., `usize`) or a range (e.g., `a..b`). ### Returns - `Option<&>::Output>`: A reference to the requested element or subslice, or `None` if the index is out of bounds. ``` -------------------------------- ### Mutably chunking a slice based on a non-decreasing predicate Source: https://docs.rs/image/latest/struct.ImageBuffer.html This example shows `chunk_by_mut` used to extract mutable subslices that are sorted according to the provided predicate. ```rust let slice = &mut [1, 1, 2, 3, 2, 3, 2, 3, 4]; let mut iter = slice.chunk_by_mut(|a, b| a <= b); assert_eq!(iter.next(), Some(&mut [1, 1, 2, 3][..])); assert_eq!(iter.next(), Some(&mut [2, 3][..])); assert_eq!(iter.next(), Some(&mut [2, 3, 4][..])); assert_eq!(iter.next(), None); ``` -------------------------------- ### Init Source: https://docs.rs/image/latest/image/buffer/struct.EnumeratePixels.html The type for initializers. ```APIDOC ## type Init = T ### Description The type for initializers. ``` -------------------------------- ### Get Element Index by Reference Source: https://docs.rs/image/latest/image/struct.ImageBuffer.html?search=std%3A%3Avec Use `element_offset` to find the index of an element within a slice given a reference to it. This method relies on pointer arithmetic and does not compare element values. It returns `None` if the reference does not point to the start of an element. ```rust let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` -------------------------------- ### Setting Color Space and Creating Buffer View Source: https://docs.rs/image/latest/src/image/images/sub_image.rs.html?search= Demonstrates setting the color space of an image buffer and creating a view of it. Asserts that the color space is preserved in a buffer-like view. ```rust buffer[(0, 0)] = crate::Rgba([0xff, 0, 0, 255]); buffer.set_rgb_primaries(Cicp::DISPLAY_P3.primaries); let view = buffer.view(0, 0, 16, 16); let view = view.view(0, 0, 16, 16); let result = view.buffer_like(); assert_eq!(buffer.color_space(), result.color_space()); ``` -------------------------------- ### as_mut_slice Source: https://docs.rs/image/latest/struct.ImageBuffer.html Returns the same slice `&mut [T]`. This method is redundant when used directly on `&mut [T]`, but it helps dereferencing other “container” types to slices, for example `Box<[T]>` or `MutexGuard<[T]>`. ```APIDOC ## as_mut_slice ### Description Returns the same slice `&mut [T]`. This method is redundant when used directly on `&mut [T]`, but it helps dereferencing other “container” types to slices, for example `Box<[T]>` or `MutexGuard<[T]>`. ### Method `&mut self` (implicitly MUTABLE) ### Endpoint N/A (Method on a struct) ### Parameters None ### Response #### Success Response - **`&mut [T]`**: A mutable slice of type T. ``` -------------------------------- ### get Source: https://docs.rs/image/latest/image/struct.ImageBuffer.html?search=std%3A%3Avec Safely gets a reference to an element or subslice by index. Returns None if the index is out of bounds. ```APIDOC ## pub fn get(&self, index: I) -> Option<&>::Output> ### Description Returns a reference to an element or subslice depending on the type of index. If given a position, returns a reference to the element at that position or `None` if out of bounds. If given a range, returns the subslice corresponding to that range, or `None` if out of bounds. ### Examples ```rust let v = [10, 40, 30]; assert_eq!(Some(&40), v.get(1)); assert_eq!(Some(&[10, 40][..]), v.get(0..2)); assert_eq!(None, v.get(3)); assert_eq!(None, v.get(0..4)); ``` ``` -------------------------------- ### take Source: https://docs.rs/image/latest/image/hooks/type.DecodingHook.html Creates an adaptor that reads at most a specified limit of bytes from the buffer. ```APIDOC ## fn take(self, limit: usize) -> Take ### Description Creates an adaptor which will read at most `limit` bytes from `self`. ### Parameters #### Query Parameters - **limit** (usize) - Required - The maximum number of bytes to read. ### Method (Implicitly called via Buf trait) ### Return Value - `Take`: An adaptor that limits the number of bytes read. ``` -------------------------------- ### rsplitn Source: https://docs.rs/image/latest/struct.ImageBuffer.html Returns an iterator over subslices separated by elements that match a predicate, limited to a specified number of items. Iteration starts from the end of the slice. ```APIDOC ## pub fn rsplitn(&self, n: usize, pred: F) -> RSplitN<'_, T, F> ### Description Returns an iterator over subslices separated by elements that match `pred` limited to returning at most `n` items. This starts at the end of the slice and works backwards. The matched element is not contained in the subslices. The last element returned, if any, will contain the remainder of the slice. ### Parameters #### Path Parameters - **n** (usize) - Required - The maximum number of items to return. - **pred** (F) - Required - A closure that returns true if an element matches the predicate. ### Examples ```rust let v = [10, 40, 30, 20, 60, 50]; for group in v.rsplitn(2, |num| *num % 3 == 0) { println!("{group:?}"); } ``` ``` -------------------------------- ### element_offset Source: https://docs.rs/image/latest/struct.ImageBuffer.html Returns the index that a reference to an element points to. Returns `None` if the element reference does not point to the start of an element within the slice. This method uses pointer arithmetic and does not compare elements. ```APIDOC ## element_offset ### Description Returns the index that an element reference points to. Returns `None` if `element` does not point to the start of an element within the slice. This method is useful for extending slice iterators like `slice::split`. Note that this uses pointer arithmetic and **does not compare elements**. To find the index of an element via comparison, use `.iter().position()` instead. ### Method `pub fn element_offset(&self, element: &T) -> Option` ### Panics Panics if `T` is zero-sized. ### Examples ```rust let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` Returning `None` with an unaligned element: ```rust let arr: &[[u32; 2]] = &[[0, 1], [2, 3]]; let flat_arr: &[u32] = arr.as_flattened(); let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap(); let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap(); assert_eq!(ok_elm, &[0, 1]); assert_eq!(weird_elm, &[1, 2]); assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0 assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1 ``` ``` -------------------------------- ### Create Image View and Buffer-Like Instance Source: https://docs.rs/image/latest/src/image/images/sub_image.rs.html Shows how to create a view of an existing image buffer and then create a new buffer with a similar structure using `buffer_like()`. Useful for creating copies or modified versions of image data. ```rust let view = buffer.view(0, 0, 16, 16); let view = view.view(0, 0, 16, 16); let result = view.buffer_like(); assert_eq!(buffer.color_space(), result.color_space()); ``` -------------------------------- ### rsplitn_mut Source: https://docs.rs/image/latest/struct.ImageBuffer.html Returns a mutable iterator over subslices separated by elements that match a predicate, limited to a specified number of items. Iteration starts from the end of the slice. ```APIDOC ## pub fn rsplitn_mut(&mut self, n: usize, pred: F) -> RSplitNMut<'_, T, F> ### Description Returns an iterator over subslices separated by elements that match `pred` limited to returning at most `n` items. This starts at the end of the slice and works backwards. The matched element is not contained in the subslices. The last element returned, if any, will contain the remainder of the slice. ### Parameters #### Path Parameters - **n** (usize) - Required - The maximum number of items to return. - **pred** (F) - Required - A closure that returns true if an element matches the predicate. ### Examples ```rust let mut s = [10, 40, 30, 20, 60, 50]; for group in s.rsplitn_mut(2, |num| *num % 3 == 0) { group[0] = 1; } assert_eq!(s, [1, 40, 30, 20, 60, 1]); ``` ``` -------------------------------- ### Pointable::Init Source: https://docs.rs/image/latest/image/buffer/struct.EnumerateRowsMut.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E The type for initializers. ```APIDOC ## type Init = T ``` -------------------------------- ### Get Pixel by Coordinates (Panics on Out of Bounds) Source: https://docs.rs/image/latest/src/image/images/buffer.rs.html?search= Gets a reference to the pixel at the specified (x, y) coordinates. Panics if the coordinates are out of bounds. ```rust pub fn get_pixel(&self, x: u32, y: u32) -> &P { match self.pixel_indices(x, y) { None => panic!( "Image index {:?} out of bounds {:?}", (x, y), (self.width, self.height) ), Some(pixel_indices) =>

::from_slice(&self.data[pixel_indices]), } } ``` -------------------------------- ### init (Pointable) Source: https://docs.rs/image/latest/image/buffer/struct.EnumerateRowsMut.html Initializes a value at the given pointer. ```APIDOC ## unsafe fn init(init: ::Init) -> usize ### Description Initializes a with the given initializer. Read more ``` -------------------------------- ### Get Image Height Source: https://docs.rs/image/latest/src/image/images/generic_image.rs.html?search=std%3A%3Avec A convenience method to get only the height of the image. It calls `dimensions` internally and returns the second element of the tuple. ```rust fn height(&self) -> u32 { let (_, h) = self.dimensions(); h } ``` -------------------------------- ### Get Image Width Source: https://docs.rs/image/latest/src/image/images/generic_image.rs.html?search=std%3A%3Avec A convenience method to get only the width of the image. It calls `dimensions` internally and returns the first element of the tuple. ```rust fn width(&self) -> u32 { let (w, _) = self.dimensions(); w } ``` -------------------------------- ### Test QOI decoder initialization and properties Source: https://docs.rs/image/latest/src/image/codecs/qoi.rs.html Tests the `QoiDecoder` by opening a sample QOI file and verifying its dimensions and color type. ```rust #[test] fn decode_test_image() { let decoder = QoiDecoder::new(File::open("tests/images/qoi/basic-test.qoi").unwrap()) .expect("Unable to read QOI file"); assert_eq!((5, 5), decoder.dimensions()); assert_eq!(ColorType::Rgba8, decoder.color_type()); } ``` -------------------------------- ### Get Mutable Pixel (Deprecated) Source: https://docs.rs/image/latest/image/flat/struct.ViewMut.html?search=std%3A%3Avec Gets a reference to the mutable pixel at the specified (x, y) coordinates. Use `get_pixel` and `put_pixel` instead. ```rust fn get_pixel_mut(&mut self, x: u32, y: u32) -> &mut Self::Pixel ``` -------------------------------- ### Create Monocolor Image with FlatSamples Source: https://docs.rs/image/latest/image/struct.FlatSamples.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to create a monocolor image using `FlatSamples::with_monocolor`. This is useful for generating a cheap source for `GenericImageView` with a uniform color, avoiding dynamic allocation. Ensure necessary imports like `image::{flat::FlatSamples, GenericImage, RgbImage, Rgb}` are included. ```rust use image::{flat::FlatSamples, GenericImage, RgbImage, Rgb}; let background = Rgb([20, 20, 20]); let bg = FlatSamples::with_monocolor(&background, 200, 200); let mut image = RgbImage::new(200, 200); // Assuming paint_something is a defined function // paint_something(&mut image); // Reset the canvas image.copy_from(&bg.as_view().unwrap(), 0, 0); ``` -------------------------------- ### Pixel Entry API Example Source: https://docs.rs/image/latest/image/trait.GenericImage.html?search=std%3A%3Avec Illustrates a potential future API for accessing and modifying pixels, offering more flexibility than direct pixel access. ```rust let px = image.pixel_entry_at(x,y); px.set_from_rgba(rgba) ``` -------------------------------- ### Deprecated: Get Error Description Source: https://docs.rs/image/latest/image/error/struct.DecodingError.html?search= Deprecated method to get a string description of the error. Use the Display implementation or `to_string()` instead. ```rust fn description(&self) -> &str ``` -------------------------------- ### Deprecated: Get 4 Channels as Tuple Source: https://docs.rs/image/latest/src/image/traits.rs.html?search=std%3A%3Avec Deprecated method to get pixel components as a 4-tuple. Remaining channels are filled with the maximum value. ```rust /// Returns the channels of this pixel as a 4 tuple. If the pixel /// has less than 4 channels the remainder is filled with the maximum value #[deprecated(since = "0.24.0", note = "Use `channels()` or `channels_mut()`")] fn channels4( &self, ) -> ( Self::Subpixel, Self::Subpixel, Self::Subpixel, Self::Subpixel, ); ``` -------------------------------- ### QoiEncoder::new Source: https://docs.rs/image/latest/image/codecs/qoi/struct.QoiEncoder.html Creates a new QoiEncoder instance that will write its output to the provided writer. This is the entry point for encoding QOI images. ```APIDOC ## `QoiEncoder::new` ### Description Creates a new encoder that writes its output to `writer`. ### Method ```rust pub fn new(writer: W) -> Self ``` ### Parameters * `writer`: The writer to which the QOI encoded data will be written. ``` -------------------------------- ### QOI Decoder Test Example Source: https://docs.rs/image/latest/src/image/codecs/qoi.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E A unit test demonstrating how to create a `QoiDecoder` from a file and assert its dimensions and color type. ```rust #[cfg(test)] mod tests { use super::*; use std::fs::File; #[test] fn decode_test_image() { let decoder = QoiDecoder::new(File::open("tests/images/qoi/basic-test.qoi").unwrap()) .expect("Unable to read QOI file"); assert_eq!((5, 5), decoder.dimensions()); assert_eq!(ColorType::Rgba8, decoder.color_type()); } } ``` -------------------------------- ### Using BiLevel for Image Palettization Source: https://docs.rs/image/latest/image/imageops/colorops/struct.BiLevel.html Demonstrates how to use the BiLevel color map to convert a grayscale image into a bi-level (black and white) image. This involves indexing colors using BiLevel and then mapping them back. ```rust use image::imageops::colorops::{index_colors, BiLevel, ColorMap}; use image::{ImageBuffer, Luma}; let (w, h) = (16, 16); // Create an image with a smooth horizontal gradient from black (0) to white (255). let gray = ImageBuffer::from_fn(w, h, |x, y| -> Luma { [(255 * x / w) as u8].into() }); // Mapping the gray image through the `BiLevel` filter should map gray pixels less than half // intensity (127) to black (0), and anything greater to white (255). let cmap = BiLevel; let palletized = index_colors(&gray, &cmap); let mapped = ImageBuffer::from_fn(w, h, |x, y| { let p = palletized.get_pixel(x, y); cmap.lookup(p.0[0] as usize) .expect("indexed color out-of-range") }); // Create an black and white image of expected output. let bw = ImageBuffer::from_fn(w, h, |x, y| -> Luma { if x <= (w / 2) { [0].into() } else { [255].into() } }); assert_eq!(mapped, bw); ``` -------------------------------- ### BitWriter Write Marker Source: https://docs.rs/image/latest/src/image/codecs/jpeg/encoder.rs.html?search= Writes a JPEG marker to the output stream. Markers are two-byte sequences starting with 0xFF, used to denote the start of segments. ```rust fn write_marker(&mut self, marker: u8) -> io::Result<()> { self.w.write_all(&[0xFF, marker]) } ``` -------------------------------- ### Splitting Off Slice Starting from Third Element Source: https://docs.rs/image/latest/image/struct.ImageBuffer.html?search= Removes and returns a subslice starting from the third element. The original slice is modified to contain only the elements before the split point. ```rust let mut slice: &[_] = &['a', 'b', 'c', 'd']; let mut tail = slice.split_off(2..).unwrap(); assert_eq!(slice, &['a', 'b']); assert_eq!(tail, &['c', 'd']); ``` -------------------------------- ### new Source: https://docs.rs/image/latest/image/type.GrayImage.html?search= Creates a new image buffer with a specified width and height, initialized with zero values. ```APIDOC ## new ### Description Creates a new image buffer based on a `Vec`. 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`. ### Method `new(width: u32, height: u32)` ### Parameters - **width**: `u32` - The width of the new image buffer. - **height**: `u32` - The height of the new image buffer. ### Returns - `ImageBuffer>` - A new image buffer. ### Panics Panics when the resulting image is larger than the maximum size of a vector. ``` -------------------------------- ### Get Underlying Array Reference (as_array) Source: https://docs.rs/image/latest/image/struct.ImageBuffer.html?search=u32+-%3E+bool Attempts to get a reference to the underlying array if the requested size `N` matches the slice length. Returns `None` otherwise. ```rust let data = [1, 2, 3]; let slice = &data[..]; let arr_ref: Option<&[i32; 3]> = slice.as_array(); assert!(arr_ref.is_some()); let short_slice = &data[..2]; let arr_ref_short: Option<&[i32; 3]> = short_slice.as_array(); assert!(arr_ref_short.is_none()); ``` -------------------------------- ### Get Mutable Underlying Array Reference (as_mut_array) Source: https://docs.rs/image/latest/image/struct.ImageBuffer.html?search=u32+-%3E+bool Attempts to get a mutable reference to the underlying array if the requested size `N` matches the slice length. Returns `None` otherwise. ```rust let mut data = [1, 2, 3]; let slice = &mut data[..]; let arr_mut_ref: Option<&mut [i32; 3]> = slice.as_mut_array(); assert!(arr_mut_ref.is_some()); let short_slice = &mut data[..2]; let arr_mut_ref_short: Option<&mut [i32; 3]> = short_slice.as_mut_array(); assert!(arr_mut_ref_short.is_none()); ``` -------------------------------- ### Manually Creating a Box from Raw Pointer and System Allocator Source: https://docs.rs/image/latest/image/hooks/type.DecodingHook.html?search=u32+-%3E+bool Demonstrates manually creating a `Box` using the system allocator by allocating memory, writing a value, and then using `from_raw_in`. This requires `allocator_api` and `slice_ptr_get` features and must be used within an `unsafe` block. ```rust #![feature(allocator_api, slice_ptr_get)] use std::alloc::{Allocator, Layout, System}; unsafe { let ptr = System.allocate(Layout::new::())?.as_mut_ptr() as *mut i32; // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `ptr`, though for this // simple example `*ptr = 5` would have worked as well. ptr.write(5); let x = Box::from_raw_in(ptr, System); } ``` -------------------------------- ### Get Raw Pointer to Slice Buffer Source: https://docs.rs/image/latest/image/struct.ImageBuffer.html?search=std%3A%3Avec Use `as_ptr` to get a read-only raw pointer to the slice's buffer. Ensure the slice outlives the pointer and the memory is not mutated through this pointer. ```rust let x = &[1, 2, 4]; let x_ptr = x.as_ptr(); unsafe { for i in 0..x.len() { assert_eq!(x.get_unchecked(i), &*x_ptr.add(i)); } } ``` -------------------------------- ### init Source: https://docs.rs/image/latest/image/buffer/struct.EnumeratePixels.html?search= Initializes an object at a given memory location using the specified initializer. ```APIDOC ## unsafe fn init(init: ::Init) -> usize ### Description Initializes a with the given initializer. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method unsafe fn init ### Endpoint N/A (Method on Trait) ### Request Example None ### Response #### Success Response (usize) The memory address where the object was initialized. ``` -------------------------------- ### init Source: https://docs.rs/image/latest/image/buffer/struct.EnumerateRows.html?search= Initializes an object with the given initializer, returning its pointer. ```APIDOC ## unsafe fn init(init: ::Init) -> usize ### Description Initializes a with the given initializer. ### Parameters #### Path Parameters - **init** (::Init) - Description: The initializer for the object. #### Return Value - **usize** - A pointer to the newly initialized object. ``` -------------------------------- ### Splitting Off Slice Starting from Third Element Mutably Source: https://docs.rs/image/latest/image/struct.ImageBuffer.html?search= Removes and returns a mutable reference to a subslice starting from the third element. The original mutable slice is adjusted to exclude the removed part. ```rust let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd']; let mut tail = slice.split_off_mut(2..).unwrap(); assert_eq!(slice, &mut ['a', 'b']); assert_eq!(tail, &mut ['c', 'd']); ``` -------------------------------- ### ImageReader Usage Examples Source: https://docs.rs/image/latest/src/image/io/image_reader_type.rs.html?search= Demonstrates how to use ImageReader to open, guess format, and decode images from files or memory. ```APIDOC ## ImageReader Usage ### Opening a file and decoding This example shows how to open a file, automatically detect its format based on the file path, and decode the image. ```no_run # use image::ImageError; # use image::ImageReader; # fn main() -> Result<(), ImageError> { let image = ImageReader::open("path/to/image.png")? .decode()?; # Ok(()) # } ``` ### Guessing format from content This example demonstrates guessing the image format from raw data in memory using a `Cursor`. ``` # use image::ImageError; # use image::ImageReader; # fn main() -> Result<(), ImageError> { use std::io::Cursor; use image::ImageFormat; let raw_data = b"P1 2 2\n\ 0 1\n\ 1 0\n"; let mut reader = ImageReader::new(Cursor::new(raw_data)) .with_guessed_format() .expect("Cursor io never fails"); assert_eq!(reader.format(), Some(ImageFormat::Pnm)); # #[cfg(feature = "pnm")] let image = reader.decode()?; # Ok(()) # } ``` ### Setting format manually If needed, you can manually specify the image format using `set_format`. ```rust # use image::ImageReader; # use image::ImageFormat; # fn main() { let mut reader = ImageReader::new(std::io::empty()); reader.set_format(ImageFormat::Png); # } ``` ``` -------------------------------- ### Convert Box to Pin (with From impl example) Source: https://docs.rs/image/latest/image/hooks/type.DecodingHook.html?search=u32+-%3E+bool Converts a Box into a Pin>, pinning the contents if T does not implement Unpin. This conversion happens in place. The example demonstrates a potentially ambiguous From impl. ```Rust struct Foo; // A type defined in this crate. impl From> for Pin { fn from(_: Box<()>) -> Pin { Pin::new(Foo) } } let foo = Box::new(()); let bar = Pin::from(foo); ``` -------------------------------- ### Get Pointer Range for Slice Source: https://docs.rs/image/latest/image/struct.ImageBuffer.html?search=std%3A%3Avec Use `as_ptr_range` to get a `Range` of two raw pointers spanning the slice. The end pointer is one past the last element. Useful for C-style interfaces. ```rust let a = [1, 2, 3]; let x = &a[1] as *const _; let y = &5 as *const _; assert!(a.as_ptr_range().contains(&x)); assert!(!a.as_ptr_range().contains(&y)); ``` -------------------------------- ### new Source: https://docs.rs/image/latest/image/struct.ImageBuffer.html?search= Creates a new image buffer with the specified width and height, initialized with zero values for all pixels. The color space is initially set to sRGB. ```APIDOC ## new ### Description Creates a new image buffer based on a `Vec`. 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`. ##### §Panics Panics when the resulting image is larger than the maximum size of a vector. ### Parameters - **width**: `u32` - The width of the new image buffer. - **height**: `u32` - The height of the new image buffer. ### Returns - `ImageBuffer>` - A new, empty image buffer. ``` -------------------------------- ### FarbfeldReader Seek Implementation Source: https://docs.rs/image/latest/src/image/codecs/farbfeld.rs.html Implements the `Seek` trait for `FarbfeldReader`, allowing seeking within the pixel data. It handles seeking from the start, end, and current position, calculating the new offset relative to the pixel data start. ```rust fn seek(&mut self, pos: SeekFrom) -> io::Result { fn parse_offset(original_offset: u64, end_offset: u64, pos: SeekFrom) -> Option { match pos { SeekFrom::Start(off) => i64::try_from(off) .ok()? .checked_sub(i64::try_from(original_offset).ok()?), SeekFrom::End(off) => { if off < i64::try_from(end_offset).unwrap_or(i64::MAX) { None } else { Some(i64::try_from(end_offset.checked_sub(original_offset)?).ok()? + off) } } SeekFrom::Current(off) => { if off < i64::try_from(end_offset).unwrap_or(i64::MAX) { None } else { Some(off) } } } } let end_offset = u64::from(self.width) * u64::from(self.height) * 4; let offset = parse_offset(self.current_offset, end_offset, pos).ok_or_else(|| { io::Error::new(io::ErrorKind::InvalidInput, "Invalid seek") })?; let new_offset = i64::try_from(self.current_offset).ok()? + offset; self.inner.seek(SeekFrom::Start(8 + new_offset as u64))?; self.current_offset = new_offset as u64; Ok(self.current_offset) } ``` -------------------------------- ### new_uninit_in Source: https://docs.rs/image/latest/image/hooks/type.DecodingHook.html Constructs a new box with uninitialized contents in the provided allocator. This is a nightly-only experimental API and is available only on non-`no_global_oom_handling` configurations. ```APIDOC ## pub fn new_uninit_in(alloc: A) -> Box, A> ### Description Constructs a new box with uninitialized contents in the provided allocator. This is a nightly-only experimental API and is available only on non-`no_global_oom_handling` configurations. ### Parameters #### Path Parameters - **alloc** (A) - Description: The allocator to use for the box. ### Response #### Success Response - **Box, A>** - A new box with uninitialized contents allocated using the provided allocator. ### Examples ```rust #![feature(allocator_api)] use std::alloc::System; let mut five = Box::::new_uninit_in(System); // Deferred initialization: five.write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5) ``` ```