From a6997e9532578696484dcec73fe626f5ef1ad45e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 10:40:20 -0800 Subject: [PATCH] image-codecs: encode a PNG from borrowed RGBA8 pixels encode_png_rgba8 writes interleaved 8-bit RGBA pixels as a PNG from a borrowed slice. encode takes an Image, which owns its buffer, so a caller holding pixels in a frame or a shared buffer had to copy the whole image before saving it. The output is the same as encode of an Image with the same pixels, no ICC profile and default metadata. A buffer whose length is not width * height * 4 is rejected with InvalidImage. --- crates/image-codecs/src/codecs/png.rs | 29 ++++++++++++++++++++++++ crates/image-codecs/src/lib.rs | 2 +- crates/image-codecs/tests/it/png_jpeg.rs | 21 +++++++++++++++++ 3 files changed, 51 insertions(+), 1 deletion(-) diff --git a/crates/image-codecs/src/codecs/png.rs b/crates/image-codecs/src/codecs/png.rs index d54d4149bf..7c98c50396 100644 --- a/crates/image-codecs/src/codecs/png.rs +++ b/crates/image-codecs/src/codecs/png.rs @@ -1265,6 +1265,35 @@ fn encode_data(raw: RawPng<'_>, opts: &EncodeOptions) -> Result, CodecEr Ok(out) } +/// Encodes interleaved 8-bit RGBA pixels, row-major with no row padding, as a PNG without +/// copying them into an [`Image`]. The output matches [`crate::encode`] of the same pixels with +/// no ICC profile and default metadata. `pixels` must hold exactly `width * height * 4` bytes. +pub fn encode_rgba8(width: u32, height: u32, pixels: &[u8], opts: &EncodeOptions) -> Result, CodecError> { + if width == 0 || height == 0 { + return Err(CodecError::InvalidImage("cannot encode an empty image".into())); + } + let expected = (width as usize) + .checked_mul(height as usize) + .and_then(|n| n.checked_mul(4)) + .ok_or_else(|| CodecError::InvalidImage("image size overflows usize".into()))?; + if pixels.len() != expected { + return Err(CodecError::InvalidImage(format!("buffer has {} bytes, expected {expected} for {width}x{height} RGBA8", pixels.len()))); + } + encode_data( + RawPng { + width, + height, + layout: ChannelLayout::Rgba, + sample: SampleType::U8, + icc: None, + cicp: None, + meta: &Metadata::default(), + data: pixels, + }, + opts, + ) +} + /// Encodes linear-light Rec. 2020 RGB as 16-bit PNG with BT.2100 PQ (`cICP`) and measured /// content-light levels (`cLLI`). Input samples are relative to 203 cd/m² diffuse white, as in /// [`crate::cicp::linearize`]. Negative and non-finite values become black; values above 10,000 diff --git a/crates/image-codecs/src/lib.rs b/crates/image-codecs/src/lib.rs index 2a91dc6ea8..67b83ced4c 100644 --- a/crates/image-codecs/src/lib.rs +++ b/crates/image-codecs/src/lib.rs @@ -50,7 +50,7 @@ pub use crate::codecs::gif_frames::{AnimationFrame, MAX_GIF_FRAMES}; pub use crate::codecs::jpeg::validate_jpeg_rgba8; pub use crate::codecs::png::{ PngDecodeRows, PngExtras, PngHeader, PngPalette, PngRowSink, PngRows, SharedBytes, encode_indexed as encode_png_indexed, - encode_pq as encode_png_pq, palette as png_palette, stereo as png_stereo, + encode_pq as encode_png_pq, encode_rgba8 as encode_png_rgba8, palette as png_palette, stereo as png_stereo, }; pub use crate::codecs::tiff::{ PhotoshopTags as TiffPhotoshopTags, TiffBands, photoshop_tags as tiff_photoshop_tags, writes_little_endian as tiff_writes_little_endian, diff --git a/crates/image-codecs/tests/it/png_jpeg.rs b/crates/image-codecs/tests/it/png_jpeg.rs index 38b40a6748..d217be5ce9 100644 --- a/crates/image-codecs/tests/it/png_jpeg.rs +++ b/crates/image-codecs/tests/it/png_jpeg.rs @@ -65,6 +65,27 @@ fn adam7_compressions() { } } +#[test] +fn png_from_borrowed_rgba8_matches_encoding_an_image() { + let img = synth(37, 23, ChannelLayout::Rgba, SampleType::U8, 9042, 0.5); + for interlace in [false, true] { + let opts = EncodeOptions { png_interlaced: interlace, ..Default::default() }; + let borrowed = encode_png_rgba8(img.width(), img.height(), img.data(), &opts).unwrap(); + assert_eq!(borrowed, encode(&img, Format::Png, &opts).unwrap(), "interlaced {interlace}"); + assert_eq!(decode(&borrowed).unwrap().data(), img.data()); + } +} + +#[test] +fn png_from_borrowed_rgba8_rejects_a_buffer_of_the_wrong_size() { + let pixels = [0u8; 4 * 4 * 4]; + let opts = EncodeOptions::default(); + for (w, h, data) in [(4, 4, &pixels[..pixels.len() - 1]), (4, 3, &pixels[..]), (0, 4, &[][..])] { + let result = encode_png_rgba8(w, h, data, &opts); + assert!(matches!(result, Err(CodecError::InvalidImage(_))), "{w}x{h} with {} bytes: {result:?}", data.len()); + } +} + #[test] fn png_palette_and_low_bit_depth_expand() { // Build a 2-bit gray PNG and a palette PNG with tRNS using the png crate.