diff --git a/crates/image-codecs/src/codecs/png.rs b/crates/image-codecs/src/codecs/png.rs index e16ef945d1..6523d56474 100644 --- a/crates/image-codecs/src/codecs/png.rs +++ b/crates/image-codecs/src/codecs/png.rs @@ -1266,6 +1266,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 ee2537625e..fc93e17966 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, encode_plain_rgba16 as encode_tiff_plain_rgba16, photoshop_tags as tiff_photoshop_tags, diff --git a/crates/image-codecs/tests/it/png_jpeg.rs b/crates/image-codecs/tests/it/png_jpeg.rs index 374ec01018..af11f72949 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.