diff --git a/Cargo.toml b/Cargo.toml index 109f4d6f71..605132484a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,16 +26,19 @@ craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", re # Native Affinity documents (craft-libs#914). craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "228f6d0c50f1fdee4c5124603602993fc79d4c9d" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2", features = ["tree"] } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "d6cd7836d364177661b0ae17f48a0805e83a5f32", features = ["tree"] } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" } # DXF tags, reader and writer (craft-libs#778, #926, #927). craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "d6cd7836d364177661b0ae17f48a0805e83a5f32" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "d6cd7836d364177661b0ae17f48a0805e83a5f32" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "d6cd7836d364177661b0ae17f48a0805e83a5f32" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "d6cd7836d364177661b0ae17f48a0805e83a5f32" } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "d6cd7836d364177661b0ae17f48a0805e83a5f32" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "d6cd7836d364177661b0ae17f48a0805e83a5f32" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "d6cd7836d364177661b0ae17f48a0805e83a5f32" } +craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "d6cd7836d364177661b0ae17f48a0805e83a5f32" } craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] } # internal vectorcraft-geom = { path = "crates/geom" } @@ -94,11 +97,7 @@ wat = "1.228" # Without `text` (glyph runs, through glifo and a second skrifa): the renderer draws the outlines # vectorcraft-text gives it. The other default features stay. vello_cpu = { version = "0.2", default-features = false, features = ["std", "png", "u8_pipeline", "f32_pipeline"] } -image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "gif", "tiff", "bmp", "tga"] } -# Without `text` and the system fonts (fontdb, harfrust and skrifa, at other versions than ours): -# SVG import reads `` from the XML itself and never gives usvg a font. A test of the SVG -# crate turns `text` on. -usvg = { version = "0.48", default-features = false, features = ["svgz"] } +image = { version = "0.25", default-features = false } # Without `simple-text` (its text shaping, the only user of rustybuzz and ttf-parser, which are # unmaintained, #1730): the PDF writer places glyphs itself. A test of the PDF crate turns it on. krilla = { version = "0.8", default-features = false, features = ["raster-images"] } @@ -109,30 +108,11 @@ flate2 = { version = "1", default-features = false, features = ["rust_backend"] rustix = { version = "1.1", default-features = false } # Zstandard decoder (pure Rust, builds for wasm32 too): the editing copy an EPS carries of its art. ruzstd = { version = "0.9.1", default-features = false, features = ["std"] } -# CCITT Group 3 and Group 4 decoder (ITU-T T.4 and T.6): EPS images read through -# `CCITTFaxDecode`. The PDF reader's hayro-syntax uses the same version. -hayro-ccitt = "0.3" # Substring search for the EPS reader's PostScript `search`. memchr = "2" # The WHATWG Encoding Standard's legacy encodings: names in legacy .ai files read in the code page # the user picks (Mac OS Roman, Korean, Japanese, Chinese). encoding_rs = "0.8.42" -jpeg-encoder = { version = "0.6", default-features = false, features = ["std"] } -gif = { version = "0.14", default-features = false, features = ["std", "raii_no_panic"] } -# CMYK image samples (vectorcraft-doc's cmyk module): the image crate's own TIFF and JPEG -# decoders, read directly (the image crate converts CMYK to RGB). -tiff = "0.11" -zune-jpeg = "0.5" -# JPEG XL decoder (pure Rust, MIT OR Apache-2.0): File › Open and Place read `.jxl` images. It is -# built without its default `rayon` feature and decodes on one thread. -jxl-oxide = { version = "0.12.6", default-features = false } -# jxl-oxide's color conversions, run on colors after their alpha is divided out. -jxl-color = "0.11.0" -# jxl-oxide's buffer allocation error, told apart from other decoding errors. -jxl-grid = "0.6.2" -# Tests: a lossless JPEG XL encoder (pure Rust, MIT OR Apache-2.0 OR Zlib) for the `.jxl` test files. -zune-jpegxl = { version = "0.5.2", default-features = false, features = ["std"] } -zune-core = "0.5" # ui egui = "0.37" diff --git a/crates/affinity/Cargo.toml b/crates/affinity/Cargo.toml index 798b0734f5..8e3bce12a9 100644 --- a/crates/affinity/Cargo.toml +++ b/crates/affinity/Cargo.toml @@ -20,4 +20,4 @@ craft-affinity = { workspace = true } proptest = { workspace = true } # The tests build containers and decode previews. crc32fast = { workspace = true } -image = { workspace = true } +craft-image-codecs = { workspace = true } diff --git a/crates/affinity/tests/it/raster.rs b/crates/affinity/tests/it/raster.rs index 794b4c4f13..46e96c2013 100644 --- a/crates/affinity/tests/it/raster.rs +++ b/crates/affinity/tests/it/raster.rs @@ -50,8 +50,8 @@ fn source_backed_tiles_retain_the_embedded_jpeg_pixels() { assert_eq!((image.width, image.height), (400, 300)); assert_eq!(image.transform, Affine::IDENTITY); let Pixels::Rgba8(pixels) = &image.pixels else { panic!("expected retained level-zero pixels") }; - let expected = image::load_from_memory(&source(&bytes)).unwrap().into_rgba8(); - assert_eq!(pixels.as_slice(), expected.as_raw()); + let expected = craft_image_codecs::decode(&source(&bytes)).unwrap().to_rgba8(); + assert_eq!(pixels.as_slice(), expected.as_slice()); assert!(pixels.as_chunks::<4>().0.iter().all(|p| p[3] == 255)); assert!(pixels.as_chunks::<4>().0.iter().any(|p| p[0] != p[1])); } diff --git a/crates/cad/Cargo.toml b/crates/cad/Cargo.toml index e529e1d4e2..53efc6eb04 100644 --- a/crates/cad/Cargo.toml +++ b/crates/cad/Cargo.toml @@ -19,6 +19,7 @@ vectorcraft-pathops = { workspace = true } vectorcraft-text = { workspace = true } kurbo = { workspace = true } image = { workspace = true } +craft-image-codecs = { workspace = true } [dev-dependencies] serde_json = { workspace = true } diff --git a/crates/cad/src/scene.rs b/crates/cad/src/scene.rs index ea3c962053..b8da4046ef 100644 --- a/crates/cad/src/scene.rs +++ b/crates/cad/src/scene.rs @@ -1403,35 +1403,38 @@ impl<'a> Scene<'a> { /// Image `im` as a file in the chosen format, and its size in pixels. fn encode_image(&self, im: &ImageObject) -> Result<(DxfImage, (u32, u32)), String> { + use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image as CodecImage, SampleType}; let blob = self.doc.image_blob(im).filter(|b| !b.bytes.is_empty()).ok_or_else(|| "an image has no pixels and was left out".to_string())?; // The pixels it converts to (RGBA, 4 bytes each) are read from its header before decoding. - let (w, h) = image::ImageReader::new(Cursor::new(blob.bytes.as_slice())) - .with_guessed_format() - .ok() - .and_then(|r| r.into_dimensions().ok()) - .ok_or_else(|| UNDECODED.to_string())?; + let info = craft_image_codecs::probe(&blob.bytes).map_err(|_| UNDECODED.to_string())?; + let (w, h) = (info.width, info.height); if u64::from(w) * u64::from(h) > MAX_IMAGE_PIXELS { return Err("an image is too large for DXF and was left out".to_string()); } - let img = image::load_from_memory(&blob.bytes).map_err(|_| UNDECODED.to_string())?; - let size = (img.width(), img.height()); - let mut bytes = vec![]; - let written = match self.o.raster { - RasterFormat::Png => img.to_rgba8().write_to(&mut Cursor::new(&mut bytes), image::ImageFormat::Png), + let decoded = craft_image_codecs::decode(&blob.bytes).map_err(|_| UNDECODED.to_string())?; + let size = decoded.dimensions(); + let mut rgba = decoded.to_rgba8(); + let bytes = match self.o.raster { + RasterFormat::Png => { + let img = CodecImage::from_raw(size.0, size.1, ChannelLayout::Rgba, SampleType::U8, rgba) + .map_err(|e| format!("an image could not be written: {e}"))?; + craft_image_codecs::encode(&img, Format::Png, &EncodeOptions::default()) + } RasterFormat::Jpeg => { // No alpha in JPEG: transparent pixels over white. - let mut rgba = img.to_rgba8(); - for p in rgba.pixels_mut() { + let mut rgb = Vec::with_capacity(rgba.len() / 4 * 3); + for p in rgba.chunks_exact_mut(4) { let a = u32::from(p[3]); - for c in 0..3 { - p[c] = ((u32::from(p[c]) * a + 255 * (255 - a)) / 255) as u8; + for c in &p[..3] { + rgb.push(((u32::from(*c) * a + 255 * (255 - a)) / 255) as u8); } } - let rgb = image::DynamicImage::ImageRgba8(rgba).to_rgb8(); - rgb.write_with_encoder(image::codecs::jpeg::JpegEncoder::new_with_quality(&mut bytes, 90)) + let img = CodecImage::from_raw(size.0, size.1, ChannelLayout::Rgb, SampleType::U8, rgb) + .map_err(|e| format!("an image could not be written: {e}"))?; + craft_image_codecs::encode(&img, Format::Jpeg, &EncodeOptions { jpeg_quality: 90, ..EncodeOptions::default() }) } - }; - written.map_err(|e| format!("an image could not be written: {e}"))?; + } + .map_err(|e| format!("an image could not be written: {e}"))?; Ok((DxfImage { name: format!("{}.{}", blob.content_key(), self.o.raster.extension()), bytes }, size)) } } diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index 84e547709d..5ad2d53478 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -852,8 +852,18 @@ fn the_cnc_preset_writes_version_2000_in_millimeters_with_type_as_paths_and_stro /// A 4 × 2 px PNG placed at (10, 20) under key `raster-1`, and before it in paint order /// `fill`'s rectangle. fn image_and_fill_doc(fill: Paint) -> Document { - let mut png = vec![]; - image::RgbaImage::from_pixel(4, 2, image::Rgba([0, 0, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let png = craft_image_codecs::encode( + &craft_image_codecs::Image::from_raw( + 4, + 2, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + [0u8, 0, 255, 255].repeat(8), + ) + .unwrap(), + craft_image_codecs::Format::Png, + ) + .unwrap(); let mut d = doc_with(|d| { let im = ImageObject { key: "raster-1".into(), @@ -1312,8 +1322,18 @@ fn a_font_height_reference_is_written_as_the_size_drawn() { #[test] fn images_link_png_or_jpeg_files() { - let mut png = vec![]; - image::RgbaImage::from_pixel(4, 2, image::Rgba([255, 0, 0, 128])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let png = craft_image_codecs::encode( + &craft_image_codecs::Image::from_raw( + 4, + 2, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + [255u8, 0, 0, 128].repeat(8), + ) + .unwrap(), + craft_image_codecs::Format::Png, + ) + .unwrap(); let mut d = doc_with(|d| { let im = ImageObject { key: "raster-1".into(), diff --git a/crates/doc/Cargo.toml b/crates/doc/Cargo.toml index 0ee88bf3b7..3826dc19c5 100644 --- a/crates/doc/Cargo.toml +++ b/crates/doc/Cargo.toml @@ -13,15 +13,15 @@ vectorcraft-geom = { workspace = true } vectorcraft-color = { workspace = true } kurbo = { workspace = true } image = { workspace = true } -tiff = { workspace = true } +craft-image-codecs = { workspace = true } +craft-tiff = { workspace = true } +flate2 = { workspace = true } # 1-bit TIFFs compressed with CCITT Group 3 (Compression 2 and 3). -hayro-ccitt = { workspace = true } -zune-jpeg = { workspace = true } +craft-stream-codecs = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } chrono = { workspace = true } [dev-dependencies] -jpeg-encoder = { workspace = true } proptest = { workspace = true } diff --git a/crates/doc/src/cmyk.rs b/crates/doc/src/cmyk.rs index 8cd3f85a4f..696c7063e5 100644 --- a/crates/doc/src/cmyk.rs +++ b/crates/doc/src/cmyk.rs @@ -9,9 +9,7 @@ use std::io::Cursor; use std::sync::Arc; -use zune_jpeg::zune_core::bytestream::ZCursor; -use zune_jpeg::zune_core::colorspace::ColorSpace; -use zune_jpeg::zune_core::options::DecoderOptions; +use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image as CodecImage, Limits as CodecLimits, SampleType}; use crate::ImageBlob; @@ -47,9 +45,7 @@ pub fn jpeg_components(bytes: &[u8]) -> Option { if !bytes.starts_with(&[0xFF, 0xD8]) { return None; } - let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default()); - d.decode_headers().ok()?; - Some(d.info()?.components as usize) + craft_image_codecs::jpeg_info(bytes).map(|info| info.layout.channels()) } fn is_tiff(bytes: &[u8]) -> bool { @@ -124,20 +120,35 @@ pub fn oversized_tiff(bytes: &[u8]) -> Option<(u32, u32)> { (tiles || strips).then_some((width, height)) } -/// The color type of TIFF `bytes` and its decoder; `None` for [`oversized_tiff`] images too. -pub(crate) fn tiff(bytes: &[u8]) -> Option<(tiff::ColorType, tiff::decoder::Decoder>)> { +/// Parsed TIFF `bytes`; `None` for non-TIFF or [`oversized_tiff`] images. +pub(crate) fn parse_tiff(bytes: &[u8]) -> Option { if !is_tiff(bytes) || oversized_tiff(bytes).is_some() { return None; } - let mut d = tiff::decoder::Decoder::new(Cursor::new(bytes)).ok()?; - Some((d.colortype().ok()?, d)) + craft_tiff::Tiff::parse(bytes).ok() +} + +/// Image metadata of TIFF `bytes`' first directory; `None` for non-TIFF or [`oversized_tiff`]. +pub(crate) fn tiff_image_info(bytes: &[u8]) -> Option { + parse_tiff(bytes)?.ifds.first()?.image().ok() +} + +/// Bit depth (8 or 16) when `info` describes a 4-channel CMYK TIFF. +fn is_cmyk_tiff_info(info: &craft_tiff::image::ImageInfo) -> Option { + if info.photometric != 5 || info.samples_per_pixel != 4 { + return None; + } + let bps = *info.bits_per_sample.first()?; + if !matches!(bps, 8 | 16) || info.bits_per_sample.iter().any(|&b| b != bps) { + return None; + } + Some(bps) } /// The Orientation tag of TIFF `bytes`' first image, of any unsigned type; `None` for other images /// and TIFFs without one. Reads only its header. pub fn tiff_orientation(bytes: &[u8]) -> Option { - let (_, mut d) = tiff(bytes)?; - d.find_tag_unsigned::(tiff::tags::Tag::Orientation).ok().flatten() + parse_tiff(bytes)?.ifds.first()?.u16(craft_tiff::tags::ORIENTATION) } /// The EXIF orientation of encoded image `bytes` when it turns or flips the pixels; `None` when @@ -145,31 +156,97 @@ pub fn tiff_orientation(bytes: &[u8]) -> Option { /// extra samples) has its Orientation tag read from its first image ([`tiff_orientation`]). Reads /// only the image's header and metadata; `None` for an [`oversized_tiff`], which no decoder opens. pub fn exif_orientation(bytes: &[u8]) -> Option { - use image::ImageDecoder as _; use image::metadata::Orientation; if oversized_tiff(bytes).is_some() { return None; } - let decoded = || image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_decoder().ok()?.orientation().ok(); - let tagged = || tiff_orientation(bytes).and_then(|v| Orientation::from_exif(u8::try_from(v).ok()?)); - decoded().or_else(tagged).filter(|o| *o != Orientation::NoTransforms) + let raw = if is_tiff(bytes) { + tiff_orientation(bytes) + } else if bytes.starts_with(&[0xFF, 0xD8]) { + jpeg_exif_bytes(bytes).map(craft_image_codecs::exif_orientation) + } else if bytes.starts_with(b"\x89PNG\r\n\x1a\n") { + png_exif_bytes(bytes).map(craft_image_codecs::exif_orientation) + } else if bytes.starts_with(b"RIFF") && bytes.get(8..12) == Some(b"WEBP") { + webp_exif_bytes(bytes).map(craft_image_codecs::exif_orientation) + } else { + None + }; + raw.and_then(|v| Orientation::from_exif(u8::try_from(v).ok()?)).filter(|o| *o != Orientation::NoTransforms) } -/// Does the TIFF `d` reads store one plane per channel (PlanarConfiguration 2)? -fn planar(d: &mut tiff::decoder::Decoder>) -> bool { - d.find_tag_unsigned::(tiff::tags::Tag::PlanarConfiguration).ok().flatten().is_some_and(|p| p != 1) +/// EXIF payload from a JPEG's APP1 `Exif\0\0` segment, if present before SOS. +fn jpeg_exif_bytes(bytes: &[u8]) -> Option<&[u8]> { + let mut i = 2usize; + while i + 4 <= bytes.len() { + if bytes[i] != 0xFF { + return None; + } + while i < bytes.len() && bytes[i] == 0xFF { + i += 1; + } + let marker = *bytes.get(i)?; + i += 1; + if marker == 0xD9 || marker == 0xDA { + return None; + } + if (0xD0..=0xD8).contains(&marker) || marker == 0x01 { + continue; + } + let len = usize::from(u16::from_be_bytes([*bytes.get(i)?, *bytes.get(i + 1)?])); + if len < 2 || i + len > bytes.len() { + return None; + } + let payload = &bytes[i + 2..i + len]; + if marker == 0xE1 && payload.starts_with(b"Exif\0\0") { + return Some(&payload[6..]); + } + i += len; + } + None } -/// The samples of the `n` pixels of the TIFF `d` reads, `per` to a pixel (the number its color -/// type has), pixel by pixel and 8 bits each (16-bit samples to their high byte), whether the file -/// stores each pixel's samples together or one plane per channel. `None` when they don't decode to -/// that many samples, which includes images whose planes together need more than the decoder's -/// limit (256 MB of samples). -pub(crate) fn read_samples(d: &mut tiff::decoder::Decoder>, n: usize, per: usize) -> Option> { - Some(match read_samples_at_depth(d, n, per)? { - Samples::Eight(v) => v, - Samples::Sixteen(v) => v.iter().map(|s| (s >> 8) as u8).collect(), - }) +/// EXIF payload from a PNG's `eXIf` chunk, if present. +fn png_exif_bytes(bytes: &[u8]) -> Option<&[u8]> { + let mut i = 8usize; + while i + 12 <= bytes.len() { + let len = usize::try_from(u32::from_be_bytes(bytes[i..i + 4].try_into().ok()?)).ok()?; + let kind = &bytes[i + 4..i + 8]; + let end = i.checked_add(8)?.checked_add(len)?; + if end + 4 > bytes.len() { + return None; + } + if kind == b"eXIf" { + return Some(&bytes[i + 8..end]); + } + if kind == b"IEND" { + return None; + } + i = end + 4; + } + None +} + +/// EXIF payload from a WebP's `EXIF` RIFF chunk, if present. +fn webp_exif_bytes(bytes: &[u8]) -> Option<&[u8]> { + let mut i = 12usize; + while i + 8 <= bytes.len() { + let kind = &bytes[i..i + 4]; + let len = usize::try_from(u32::from_le_bytes(bytes[i + 4..i + 8].try_into().ok()?)).ok()?; + let end = i.checked_add(8)?.checked_add(len)?; + if end > bytes.len() { + return None; + } + if kind == b"EXIF" { + return Some(&bytes[i + 8..end]); + } + i = end + (len & 1); + } + None +} + +/// Does the TIFF `ifd` store one plane per channel (PlanarConfiguration 2)? +fn planar(ifd: &craft_tiff::Ifd) -> bool { + ifd.u16(craft_tiff::tags::PLANAR_CONFIGURATION).is_some_and(|p| p != 1) } /// Samples of an image, pixel by pixel, at the depth its file stores them. @@ -195,33 +272,22 @@ enum SampleSlice<'a> { Sixteen(&'a [u16]), } -/// [`read_samples`], keeping 16-bit samples at 16 bits. -fn read_samples_at_depth(d: &mut tiff::decoder::Decoder>, n: usize, per: usize) -> Option { - let mut buf = tiff::decoder::DecodingResult::U8(Vec::new()); - let layout = d.read_image_to_buffer(&mut buf).ok()?; - match buf { - tiff::decoder::DecodingResult::U8(v) => chunky(v, layout.planes, n, per).map(Samples::Eight), - tiff::decoder::DecodingResult::U16(v) => chunky(v, layout.planes, n, per).map(Samples::Sixteen), +/// Decode CMYK TIFF `bytes` (8 or 16 bits, chunky or planar) via `craft-image-codecs`. +fn decode_cmyk_tiff_samples(bytes: &[u8], info: &craft_tiff::image::ImageInfo) -> Option { + let _ = is_cmyk_tiff_info(info)?; + let _ = pixels(info.width, info.height)?; + let opts = craft_image_codecs::DecodeOptions { limits: CodecLimits::unlimited(), keep_orientation: true }; + let img = craft_image_codecs::decode_as_with(Format::Tiff, bytes, &opts).ok()?; + if img.layout != ChannelLayout::Cmyk || img.width != info.width || img.height != info.height { + return None; + } + match img.sample_type { + SampleType::U8 => Some(Samples::Eight(img.into_data())), + SampleType::U16 => Some(Samples::Sixteen(img.to_u16_samples()?)), _ => None, } } -/// `data`, the samples of `n` pixels, `per` to a pixel, stored in `planes` planes, as the samples -/// pixel by pixel; `None` when it doesn't hold that many samples or a plane per sample. -fn chunky(data: Vec, planes: usize, n: usize, per: usize) -> Option> { - if Some(data.len()) != n.checked_mul(per) { - return None; - } - if planes <= 1 { - return Some(data); - } - if planes != per { - return None; - } - let planes: Vec<&[T]> = data.chunks_exact(n).collect(); - Some((0..n).flat_map(|i| planes.iter().filter_map(move |p| p.get(i).copied())).collect()) -} - /// The color space an ICC profile's header names (bytes 16 to 19, such as `RGB `, `GRAY` or /// `CMYK`); `None` when `icc` is shorter than a header. pub fn icc_color_space(icc: &[u8]) -> Option<[u8; 4]> { @@ -231,24 +297,65 @@ pub fn icc_color_space(icc: &[u8]) -> Option<[u8; 4]> { icc.get(16..20)?.try_into().ok() } -/// The ICC profile of TIFF tag 34675 (ICCProfile) of the image `d` reads; `None` without one. -fn tiff_icc(d: &mut tiff::decoder::Decoder>) -> Option> { - d.get_tag_u8_vec(tiff::tags::Tag::IccProfile).ok().filter(|icc| !icc.is_empty()) +/// The ICC profile of TIFF tag 34675 (ICCProfile) of `ifd`; `None` without one. +fn tiff_icc(ifd: &craft_tiff::Ifd) -> Option> { + ifd.bytes(craft_tiff::tags::ICC_PROFILE).filter(|icc| !icc.is_empty()).map(|icc| icc.to_vec()) } -/// The ICC profile of TIFF `bytes`' first image (tag 34675), read with the `tiff` decoder's own -/// limits, whatever the size of the image; `None` for other images and TIFFs without one. +/// The ICC profile of TIFF `bytes`' first image (tag 34675); `None` for other images and TIFFs +/// without one. pub fn tiff_icc_profile(bytes: &[u8]) -> Option> { - let (_, mut d) = tiff(bytes)?; - tiff_icc(&mut d) + tiff_icc(parse_tiff(bytes)?.ifds.first()?) } /// The ICC profile of a JPEG, put together from all its numbered `ICC_PROFILE` APP2 segments; /// `None` without one. fn jpeg_icc(bytes: &[u8]) -> Option> { - let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default()); - d.decode_headers().ok()?; - d.icc_profile().filter(|icc| !icc.is_empty()) + if !bytes.starts_with(&[0xFF, 0xD8]) { + return None; + } + let mut chunks: Vec<(u8, u8, &[u8])> = Vec::new(); + let mut i = 2usize; + while i + 4 <= bytes.len() { + if bytes[i] != 0xFF { + break; + } + while i < bytes.len() && bytes[i] == 0xFF { + i += 1; + } + let Some(&marker) = bytes.get(i) else { break }; + i += 1; + if marker == 0xD9 || marker == 0xDA { + break; + } + if (0xD0..=0xD8).contains(&marker) || marker == 0x01 { + continue; + } + let len = usize::from(u16::from_be_bytes([*bytes.get(i)?, *bytes.get(i + 1)?])); + if len < 2 || i + len > bytes.len() { + break; + } + let payload = &bytes[i + 2..i + len]; + if marker == 0xE2 && payload.starts_with(b"ICC_PROFILE\0") && payload.len() >= 14 { + let seq = payload[12]; + let total = payload[13]; + if seq >= 1 && total >= seq { + chunks.push((seq, total, &payload[14..])); + } + } + i += len; + } + if chunks.is_empty() { + return None; + } + let total = chunks[0].1; + chunks.sort_by_key(|c| c.0); + let mut out = Vec::new(); + for expected in 1..=total { + let (_, _, data) = chunks.iter().find(|c| c.0 == expected && c.1 == total)?; + out.extend_from_slice(data); + } + (!out.is_empty()).then_some(out) } /// `icc` when it is a profile of CMYK colors, which the samples of a CMYK image are in. @@ -267,15 +374,12 @@ struct CmykSource { /// The samples of CMYK TIFF `bytes` (8 or 16 bits), their inks together or one plane per ink, with /// the TIFF's CMYK ICC profile; `None` for other images and ones larger than [`MAX_CMYK_PIXELS`]. fn tiff_source(bytes: &[u8]) -> Option { - let (kind, mut d) = tiff(bytes)?; - if !matches!(kind, tiff::ColorType::CMYK(8 | 16)) { - return None; - } - let (width, height) = d.dimensions().ok()?; - let n = usize::try_from(pixels(width, height)?).ok()?; - let icc = cmyk_icc(tiff_icc(&mut d)); - let samples = read_samples_at_depth(&mut d, n, 4)?; - Some(CmykSource { width, height, samples, icc }) + let tiff = parse_tiff(bytes)?; + let ifd = tiff.ifds.first()?; + let info = ifd.image().ok()?; + let samples = decode_cmyk_tiff_samples(bytes, &info)?; + let icc = cmyk_icc(tiff_icc(ifd)); + Some(CmykSource { width: info.width, height: info.height, samples, icc }) } /// The ink amounts of a four-component JPEG, 8 bits each, with its CMYK ICC profile. @@ -289,57 +393,38 @@ fn jpeg_source(bytes: &[u8]) -> Option { /// above 0, and carrying `icc` as tag 34675 (ICCProfile, of type UNDEFINED); `None` when it can't be /// written. fn write_cmyk_tiff(width: u32, height: u32, samples: SampleSlice<'_>, ppi: Option<(f64, f64)>, icc: Option<&[u8]>) -> Option> { - use tiff::encoder::colortype::{CMYK8, CMYK16, ColorType}; - use tiff::encoder::{Compression, ImageEncoder, Rational, TiffEncoder, TiffKind, compression::DeflateLevel}; - use tiff::tags::{ResolutionUnit, Tag}; - fn tags( - img: &mut ImageEncoder<'_, W, C, K>, - ppi: Option<(f64, f64)>, - icc: Option<&[u8]>, - ) -> Option<()> { - if let Some((x, y)) = ppi.filter(|(x, y)| [x, y].iter().all(|v| v.is_finite() && **v > 0.0)) { - // Ten-thousandths of a pixel per inch. - let r = |v: f64| Rational { n: (v * 10_000.0).round() as u32, d: 10_000 }; - img.encoder().write_tag(Tag::XResolution, r(x)).ok()?; - img.encoder().write_tag(Tag::YResolution, r(y)).ok()?; - img.encoder().write_tag(Tag::ResolutionUnit, ResolutionUnit::Inch).ok()?; - } - if let Some(icc) = icc { - img.encoder().write_tag(Tag::IccProfile, Undefined(icc)).ok()?; - } - Some(()) - } - let mut out = Cursor::new(Vec::new()); - let mut enc = TiffEncoder::new(&mut out).ok()?.with_compression(Compression::Deflate(DeflateLevel::Balanced)); - match samples { - SampleSlice::Eight(data) => { - let mut img = enc.new_image::(width, height).ok()?; - tags(&mut img, ppi, icc)?; - img.write_data(data).ok()?; - } - SampleSlice::Sixteen(data) => { - let mut img = enc.new_image::(width, height).ok()?; - tags(&mut img, ppi, icc)?; - img.write_data(data).ok()?; - } - } - Some(out.into_inner()) -} + use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value, tags}; + use flate2::{Compression, write::ZlibEncoder}; + use std::io::Write as _; -/// Bytes written as a TIFF field of type UNDEFINED, the type of an embedded ICC profile. -struct Undefined<'a>(&'a [u8]); + let (bps, raw): (u16, Vec) = match samples { + SampleSlice::Eight(data) => (8, data.to_vec()), + SampleSlice::Sixteen(data) => (16, data.iter().flat_map(|s| s.to_le_bytes()).collect()), + }; + let mut enc = ZlibEncoder::new(Vec::new(), Compression::default()); + enc.write_all(&raw).ok()?; + let compressed = enc.finish().ok()?; -impl tiff::encoder::TiffValue for Undefined<'_> { - const BYTE_LEN: u8 = 1; - const FIELD_TYPE: tiff::tags::Type = tiff::tags::Type::UNDEFINED; + let mut ifd = IfdBuilder::new(); + ifd.set(tags::IMAGE_WIDTH, Value::Long(vec![width])) + .set(tags::IMAGE_LENGTH, Value::Long(vec![height])) + .set(tags::BITS_PER_SAMPLE, Value::Short(vec![bps; 4])) + .set(tags::COMPRESSION, Value::Short(vec![8])) + .set(tags::PHOTOMETRIC, Value::Short(vec![5])) + .set(tags::SAMPLES_PER_PIXEL, Value::Short(vec![4])) + .set(tags::PLANAR_CONFIGURATION, Value::Short(vec![1])) + .set(tags::SAMPLE_FORMAT, Value::Short(vec![1; 4])) + .set_image(ImageData::Strips { rows_per_strip: height.max(1), strips: vec![compressed] }); - fn count(&self) -> usize { - self.0.len() + if let Some((x, y)) = ppi.filter(|(x, y)| [x, y].iter().all(|v| v.is_finite() && **v > 0.0)) { + ifd.set(tags::X_RESOLUTION, Value::Rational(vec![((x * 10_000.0).round() as u32, 10_000)])) + .set(tags::Y_RESOLUTION, Value::Rational(vec![((y * 10_000.0).round() as u32, 10_000)])) + .set(tags::RESOLUTION_UNIT, Value::Short(vec![2])); } - - fn data(&self) -> std::borrow::Cow<'_, [u8]> { - std::borrow::Cow::Borrowed(self.0) + if let Some(icc) = icc { + ifd.set(tags::ICC_PROFILE, Value::Undefined(icc.to_vec())); } + TiffWriter::new(ByteOrder::Little, false).write(&[ifd]).ok() } impl ImageBlob { @@ -358,25 +443,22 @@ impl ImageBlob { /// Does the image hold CMYK samples (a four-component JPEG or a CMYK TIFF)? Reads only its /// header. pub fn is_cmyk(&self) -> bool { - jpeg_components(&self.bytes) == Some(4) || tiff(&self.bytes).is_some_and(|(t, _)| matches!(t, tiff::ColorType::CMYK(8 | 16))) + jpeg_components(&self.bytes) == Some(4) || tiff_image_info(&self.bytes).is_some_and(|info| is_cmyk_tiff_info(&info).is_some()) } /// Does the image hold CMYK samples of 16 bits (a CMYK TIFF), which [`Self::cmyk`] gives at 8 /// bits? Reads only its header. pub fn is_cmyk16(&self) -> bool { - tiff(&self.bytes).is_some_and(|(t, _)| matches!(t, tiff::ColorType::CMYK(16))) + tiff_image_info(&self.bytes).is_some_and(|info| is_cmyk_tiff_info(&info) == Some(16)) } /// The width and height a JPEG or TIFF says it has, for any color type. Reads only its header. pub fn header_size(&self) -> Option<(u32, u32)> { let bytes = self.bytes.as_slice(); if bytes.starts_with(&[0xFF, 0xD8]) { - let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default()); - d.decode_headers().ok()?; - let (w, h) = d.dimensions()?; - return Some((u32::try_from(w).ok()?, u32::try_from(h).ok()?)); + return craft_image_codecs::jpeg_info(bytes).map(|info| (info.width, info.height)); } - tiff(bytes).and_then(|(_, mut d)| d.dimensions().ok()) + tiff_image_info(bytes).map(|info| (info.width, info.height)) } /// The ink amounts of a CMYK image; `None` for other images, and ones that can't be decoded @@ -394,11 +476,11 @@ impl ImageBlob { if jpeg_components(bytes) == Some(4) { return cmyk_icc(jpeg_icc(bytes)); } - let (kind, mut d) = tiff(bytes)?; - if !matches!(kind, tiff::ColorType::CMYK(8 | 16)) { - return None; - } - cmyk_icc(tiff_icc(&mut d)) + let tiff = parse_tiff(bytes)?; + let ifd = tiff.ifds.first()?; + let info = ifd.image().ok()?; + let _ = is_cmyk_tiff_info(&info)?; + cmyk_icc(tiff_icc(ifd)) } /// The ink amounts around pixel (`x`, `y`) of a CMYK image, in the pixel space of an image @@ -449,45 +531,27 @@ fn sample_inks(inks: &Inks, x: f64, y: f64, size: u32) -> Option<[u8; 4]> { Some(sum.map(c)) } -/// The ink amounts of a four-component JPEG (its samples inverted back; YCCK converted to CMYK -/// first, as JPEG readers do). +/// The ink amounts of a four-component JPEG. fn jpeg_inks(bytes: &[u8]) -> Option { - let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default()); - d.decode_headers().ok()?; - let space = d.input_colorspace()?; - if d.info()?.components != 4 || !matches!(space, ColorSpace::CMYK | ColorSpace::YCCK) { + let limits = CodecLimits { max_pixels: MAX_CMYK_PIXELS, ..CodecLimits::default() }; + let img = craft_image_codecs::decode_as_with(Format::Jpeg, bytes, &limits).ok()?; + if img.layout() != ChannelLayout::Cmyk || img.sample_type() != SampleType::U8 { return None; } - let (w, h) = d.dimensions()?; - let (w, h) = (u32::try_from(w).ok()?, u32::try_from(h).ok()?); + let (w, h) = img.dimensions(); pixels(w, h)?; - d.set_options(DecoderOptions::default().jpeg_set_out_colorspace(space)); - let mut data = d.decode().ok()?; - for p in data.as_chunks_mut::<4>().0 { - if space == ColorSpace::YCCK { - let [y, cb, cr] = [p[0], p[1], p[2]].map(f32::from); - // libjpeg's YCCK → CMYK: the complement of the YCbCr colour's RGB. - p[0] = (434.456 - y - 1.402 * cr).clamp(0.0, 255.0) as u8; - p[1] = (119.541 - y + 0.344 * cb + 0.714 * cr).clamp(0.0, 255.0) as u8; - p[2] = (481.816 - y - 1.772 * cb).clamp(0.0, 255.0) as u8; - } - for v in p.iter_mut() { - *v = 255 - *v; - } - } - Inks::new(w, h, data) + Inks::new(w, h, img.into_data()) } /// The ink amounts of a CMYK TIFF (16-bit samples to 8 bits), its inks stored together or one plane /// per ink. fn tiff_inks(bytes: &[u8]) -> Option { - let (kind, mut d) = tiff(bytes)?; - let (w, h) = d.dimensions().ok()?; - if !matches!(kind, tiff::ColorType::CMYK(8 | 16)) { - return None; - } - let n = usize::try_from(pixels(w, h)?).ok()?; - Inks::new(w, h, read_samples(&mut d, n, 4)?) + let info = tiff_image_info(bytes)?; + let data = match decode_cmyk_tiff_samples(bytes, &info)? { + Samples::Eight(v) => v, + Samples::Sixteen(v) => v.into_iter().map(|s| (s >> 8) as u8).collect(), + }; + Inks::new(info.width, info.height, data) } /// CMYK TIFF `bytes` that no orientation turns ([`turned_cmyk`] stores the others) as Open and @@ -497,8 +561,9 @@ fn tiff_inks(bytes: &[u8]) -> Option { /// whose inks [`ImageBlob::cmyk`] doesn't read. pub fn stored_cmyk_tiff(bytes: &[u8], ppi: Option<(f64, f64)>) -> Option> { let source = tiff_source(bytes)?; - let (_, mut d) = tiff(bytes)?; - if !planar(&mut d) { + let tiff = parse_tiff(bytes)?; + let ifd = tiff.ifds.first()?; + if !planar(ifd) { return Some(bytes.to_vec()); } write_cmyk_tiff(source.width, source.height, source.samples.as_slice(), ppi, source.icc.as_deref()) @@ -535,23 +600,35 @@ pub fn turned_cmyk(bytes: &[u8], orientation: image::metadata::Orientation, ppi: /// is rounded to 8 bits. The samples may be stored together or one plane per channel. `None` for /// other images and ones larger than [`MAX_CMYK_PIXELS`]. pub fn extra_samples_tiff_rgba(bytes: &[u8], rgb: impl Fn([f32; 4]) -> [f32; 3]) -> Option { - use tiff::tags::Tag; - let (kind, mut d) = tiff(bytes)?; - let (w, h) = d.dimensions().ok()?; - // 0: white is zero, 1: black is zero (the two grayscales). - let photometric = d.find_tag_unsigned::(Tag::PhotometricInterpretation).ok().flatten(); + let tiff = parse_tiff(bytes)?; + let ifd = tiff.ifds.first()?; + let info = ifd.image().ok()?; + let bps = *info.bits_per_sample.first()?; + if !matches!(bps, 8 | 16) || info.bits_per_sample.iter().any(|&b| b != bps) { + return None; + } + let is_cmyka = info.photometric == 5 && info.samples_per_pixel == 5; + let is_gray_extra = matches!(info.photometric, 0 | 1) && info.samples_per_pixel >= 2; + if !is_cmyka && !is_gray_extra { + return None; + } + let (w, h) = (info.width, info.height); + let n = usize::try_from(pixels(w, h)?).ok()?; // ExtraSamples 1: associated alpha (premultiplied colour), 2: unassociated alpha, 0: not alpha. - let extra = d.find_tag_unsigned_vec::(Tag::ExtraSamples).ok().flatten().and_then(|v| v.first().copied()); - // (samples in a pixel, how many of them are its colour, is the next one alpha?) - let (samples, colour, alpha) = match kind { - tiff::ColorType::CMYKA(8 | 16) => (5, 4, true), - tiff::ColorType::Multiband { bit_depth: 8 | 16, num_samples: n @ 2.. } if matches!(photometric, Some(0 | 1)) => { - (usize::from(n), 1, matches!(extra, Some(1 | 2))) - } + let extra = ifd.u64s(craft_tiff::tags::EXTRA_SAMPLES).and_then(|v| v.first().copied()).and_then(|v| u16::try_from(v).ok()); + let opts = craft_image_codecs::DecodeOptions { limits: CodecLimits::unlimited(), keep_orientation: true }; + let img = craft_image_codecs::decode_as_with(Format::Tiff, bytes, &opts).ok()?; + let (samples, colour, alpha) = match img.layout { + ChannelLayout::CmykA if is_cmyka => (5, 4, true), + ChannelLayout::GrayA if is_gray_extra => (2, 1, true), + ChannelLayout::Gray if is_gray_extra => (1, 1, false), + _ => return None, + }; + let data = match img.sample_type { + SampleType::U8 => Samples::Eight(img.into_data()), + SampleType::U16 => Samples::Sixteen(img.to_u16_samples()?), _ => return None, }; - let n = usize::try_from(pixels(w, h)?).ok()?; - let data = read_samples_at_depth(&mut d, n, samples)?; // Sample `i` of the image, 0..1. let level_at = |i: usize| match &data { Samples::Eight(v) => v.get(i).map(|&s| f32::from(s) / 255.0), @@ -576,7 +653,6 @@ pub fn extra_samples_tiff_rgba(bytes: &[u8], rgb: impl Fn([f32; 4]) -> [f32; 3]) }; let [r, g, b] = match colour { 4 => rgb([level(0), level(1), level(2), level(3)]), - _ if photometric == Some(0) => [1.0 - level(0); 3], _ => [level(0); 3], }; out.extend([r, g, b].map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)); @@ -595,7 +671,7 @@ pub enum Group3Error { /// doesn't read, such as T.4's uncompressed mode, or a row of the wrong width), or a tile is /// larger than [`crate::MAX_RASTER_ALLOC`] allows as RGBA. #[error("could not decode image: {0}")] - Damaged(hayro_ccitt::DecodeError), + Damaged(craft_stream_codecs::CcittErrorKind), } /// The pixels of a 1-bit TIFF compressed with CCITT Group 3, which the image decoder doesn't read, @@ -610,151 +686,138 @@ pub enum Group3Error { /// an error when the pixels would take more than [`crate::MAX_RASTER_ALLOC`] as RGBA, a tile is /// larger than that allowance, or a strip or tile can't be decoded or ends before its last row. pub fn group3_tiff_rgba(bytes: &[u8]) -> Option> { - use hayro_ccitt::{DecodeError, DecodeSettings, DecoderContext, EncodingMode}; - use tiff::tags::Tag; - let (kind, mut d) = tiff(bytes)?; - let compression = d.find_tag_unsigned::(Tag::Compression).ok().flatten()?; - let (w, h) = d.dimensions().ok()?; - if kind != tiff::ColorType::Gray(1) || !matches!(compression, 2 | 3) || w == 0 || h == 0 { + use craft_stream_codecs::{CcittErrorKind, CcittParams, decode_ccitt_raw}; + use craft_tiff::tags; + let tiff = parse_tiff(bytes)?; + let ifd = tiff.ifds.first()?; + let info = ifd.image().ok()?; + let compression = info.compression; + let (w, h) = (info.width, info.height); + if info.samples_per_pixel != 1 || info.bits_per_sample != [1] || !matches!(compression, 2 | 3) || w == 0 || h == 0 { return None; } // The level of a 0 bit (a white run): white when white is zero (0), black when black is zero (1). - let zero = match d.find_tag_unsigned::(Tag::PhotometricInterpretation).ok().flatten() { - Some(0) => u8::MAX, - Some(1) => 0, + let zero = match info.photometric { + 0 => u8::MAX, + 1 => 0, _ => return None, }; if u64::from(w) * u64::from(h) > crate::MAX_RASTER_ALLOC / 4 { return Some(Err(Group3Error::TooLarge { w, h })); } - let t4_options = d.find_tag_unsigned::(Tag::Unknown(292)).ok().flatten().unwrap_or(0); - let lsb_first = d.find_tag_unsigned::(Tag::FillOrder).ok().flatten() == Some(2); - let encoding = if compression == 3 && t4_options & 1 != 0 { - // Each row's tag bit says how it is coded. - EncodingMode::Group3_2D { k: 2 } - } else { - EncodingMode::Group3_1D - }; + let t4_options = ifd.u32(292).unwrap_or(0); + let lsb_first = ifd.u16(266) == Some(2); + let k = if compression == 3 && t4_options & 1 != 0 { 2 } else { 0 }; // The width and height of each strip or tile, and the tags of their offsets and byte counts. - let tiled = d.get_chunk_type() == tiff::decoder::ChunkType::Tile; - let (cw, ch, offsets, counts) = if tiled { - let tw = d.find_tag_unsigned::(Tag::TileWidth).ok().flatten().filter(|&v| v > 0)?; - let th = d.find_tag_unsigned::(Tag::TileLength).ok().flatten().filter(|&v| v > 0)?; - (tw, th, Tag::TileOffsets, Tag::TileByteCounts) + let tiled = ifd.contains(tags::TILE_WIDTH); + let (cw, ch) = if tiled { + let tw = ifd.u32(tags::TILE_WIDTH).filter(|&v| v > 0)?; + let th = ifd.u32(tags::TILE_LENGTH).filter(|&v| v > 0)?; + (tw, th) } else { - let rows = d.find_tag_unsigned::(Tag::RowsPerStrip).ok().flatten().filter(|&v| v > 0).map_or(h, |r| r.min(h)); - (w, rows, Tag::StripOffsets, Tag::StripByteCounts) + let rows = ifd.u32(tags::ROWS_PER_STRIP).filter(|&v| v > 0).map_or(h, |r| r.min(h)); + (w, rows) }; - let damaged = |e: DecodeError| Some(Err(Group3Error::Damaged(e))); + let damaged = |e: CcittErrorKind| Some(Err(Group3Error::Damaged(e))); // A tile is held to the allowance the image is held to; a strip is no larger than the image. if u64::from(cw) * u64::from(ch) > crate::MAX_RASTER_ALLOC / 4 { - return damaged(DecodeError::Overflow); + return damaged(CcittErrorKind::Overflow); } - let offsets = d.find_tag_unsigned_vec::(offsets).ok().flatten().unwrap_or_default(); - let counts = d.find_tag_unsigned_vec::(counts).ok().flatten().unwrap_or_default(); + let offsets = &info.offsets; + let counts = &info.byte_counts; let across = w.div_ceil(cw); let chunks = u64::from(across) * u64::from(h.div_ceil(ch)); if chunks > offsets.len().min(counts.len()) as u64 { - return damaged(DecodeError::UnexpectedEof); + return damaged(CcittErrorKind::UnexpectedEof); } let mut gray = vec![zero; usize::try_from(u64::from(w) * u64::from(h)).ok()?]; let mut budget = bytes.len(); + let stride = (cw as usize).div_ceil(8); for (i, (&offset, &count)) in (0..chunks).zip(offsets.iter().zip(&counts)) { let (x0, y0) = (u32::try_from(i % u64::from(across)).ok()? * cw, u32::try_from(i / u64::from(across)).ok()? * ch); let Some(start) = usize::try_from(offset).ok().filter(|&s| s <= bytes.len()) else { - return damaged(DecodeError::UnexpectedEof); + return damaged(CcittErrorKind::UnexpectedEof); }; let len = usize::try_from(count).unwrap_or(usize::MAX).min(bytes.len() - start).min(budget); budget -= len; let data = bytes.get(start..start + len)?; let data: std::borrow::Cow<[u8]> = if lsb_first { data.iter().map(|b| b.reverse_bits()).collect() } else { data.into() }; - let settings = DecodeSettings { - columns: cw, - // A tile is coded whole; the last strip only has the image's remaining rows. - rows: if tiled { ch } else { ch.min(h - y0) }, + // A tile is coded whole; the last strip only has the image's remaining rows. + let target_rows = if tiled { ch } else { ch.min(h - y0) }; + let params = CcittParams { + k, + columns: i64::from(cw), + rows: i64::from(target_rows), end_of_block: compression == 3, end_of_line: compression == 3, - rows_are_byte_aligned: compression == 2, - encoding, - invert_black: false, + encoded_byte_align: compression == 2, + black_is_1: true, }; - let mut rows = Rows { out: &mut gray, width: w, height: h, x0, y0, x: 0, y: 0, zero }; - if let Err(e) = hayro_ccitt::decode(&data, &mut rows, &mut DecoderContext::new(settings)) { + let Ok(out) = decode_ccitt_raw(&data, ¶ms, target_rows) else { + return damaged(CcittErrorKind::Overflow); + }; + if let Some(e) = out.error { return damaged(e); } - // The data ended, or six EOL codes came, before the strip's or tile's last row. - if rows.y < settings.rows { - return damaged(DecodeError::UnexpectedEof); + if out.rows_decoded < target_rows { + return damaged(CcittErrorKind::UnexpectedEof); + } + let max_y = target_rows.min(h - y0); + let max_x = cw.min(w - x0); + for y in 0..max_y { + let src_row = &out.data[y as usize * stride..][..stride]; + let dst_off = (y0 + y) as usize * w as usize + x0 as usize; + for x in 0..max_x as usize { + let bit = (src_row[x / 8] >> (7 - (x % 8))) & 1; + gray[dst_off + x] = if bit == 0 { zero } else { u8::MAX - zero }; + } } } let gray = image::GrayImage::from_raw(w, h, gray)?; Some(Ok(image::DynamicImage::ImageLuma8(gray).to_rgba8())) } -/// Where a strip or tile of a Group 3 TIFF ([`group3_tiff_rgba`]) puts its decoded pixels: `out` -/// holds the image's levels row by row, `width` × `height`, and the strip or tile starts at (`x0`, -/// `y0`). Pixels past the image's right or bottom edge (a tile's padding) are dropped. -struct Rows<'a> { - out: &'a mut [u8], - width: u32, - height: u32, - x0: u32, - y0: u32, - /// The next pixel in the strip or tile. - x: u64, - y: u32, - /// The level of a white run. - zero: u8, -} - -impl Rows<'_> { - /// The next `n` pixels of the row, a white run's or a black run's. - fn run(&mut self, white: bool, n: u64) { - let level = if white { self.zero } else { u8::MAX - self.zero }; - let row = u64::from(self.y0) + u64::from(self.y); - let left = u64::from(self.x0) + self.x; - let right = left.saturating_add(n).min(u64::from(self.width)); - if row < u64::from(self.height) && left < right { - let at = row * u64::from(self.width); - if let (Ok(a), Ok(b)) = (usize::try_from(at + left), usize::try_from(at + right)) - && let Some(px) = self.out.get_mut(a..b) - { - px.fill(level); - } - } - self.x = self.x.saturating_add(n); - } -} - -impl hayro_ccitt::Decoder for Rows<'_> { - fn push_pixel(&mut self, white: bool) { - self.run(white, 1); - } - - fn push_pixel_chunk(&mut self, white: bool, chunk_count: u32) { - self.run(white, u64::from(chunk_count) * 8); - } - - fn next_line(&mut self) { - self.y = self.y.saturating_add(1); - self.x = 0; - } -} - #[cfg(test)] mod tests { use super::*; + fn test_extra_tiff_u8(width: u32, height: u32, photometric: u16, spp: u16, extra: u16, data: &[u8]) -> Vec { + use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value, tags}; + let mut ifd = IfdBuilder::new(); + ifd.set(tags::IMAGE_WIDTH, Value::Long(vec![width])) + .set(tags::IMAGE_LENGTH, Value::Long(vec![height])) + .set(tags::BITS_PER_SAMPLE, Value::Short(vec![8; usize::from(spp)])) + .set(tags::COMPRESSION, Value::Short(vec![1])) + .set(tags::PHOTOMETRIC, Value::Short(vec![photometric])) + .set(tags::SAMPLES_PER_PIXEL, Value::Short(vec![spp])) + .set(tags::PLANAR_CONFIGURATION, Value::Short(vec![1])) + .set(tags::SAMPLE_FORMAT, Value::Short(vec![1; usize::from(spp)])) + .set(tags::EXTRA_SAMPLES, Value::Short(vec![extra])) + .set_image(ImageData::Strips { rows_per_strip: height, strips: vec![data.to_vec()] }); + TiffWriter::new(ByteOrder::Little, false).write(&[ifd]).unwrap() + } + + fn test_extra_tiff_u16(width: u32, height: u32, photometric: u16, spp: u16, extra: u16, data: &[u16]) -> Vec { + use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value, tags}; + let raw: Vec = data.iter().flat_map(|s| s.to_le_bytes()).collect(); + let mut ifd = IfdBuilder::new(); + ifd.set(tags::IMAGE_WIDTH, Value::Long(vec![width])) + .set(tags::IMAGE_LENGTH, Value::Long(vec![height])) + .set(tags::BITS_PER_SAMPLE, Value::Short(vec![16; usize::from(spp)])) + .set(tags::COMPRESSION, Value::Short(vec![1])) + .set(tags::PHOTOMETRIC, Value::Short(vec![photometric])) + .set(tags::SAMPLES_PER_PIXEL, Value::Short(vec![spp])) + .set(tags::PLANAR_CONFIGURATION, Value::Short(vec![1])) + .set(tags::SAMPLE_FORMAT, Value::Short(vec![1; usize::from(spp)])) + .set(tags::EXTRA_SAMPLES, Value::Short(vec![extra])) + .set_image(ImageData::Strips { rows_per_strip: height, strips: vec![raw] }); + TiffWriter::new(ByteOrder::Little, false).write(&[ifd]).unwrap() + } + #[test] fn a_cmyk_tiff_with_alpha_reads_as_rgba() { - use tiff::encoder::{TiffEncoder, colortype::CMYKA8}; // 2 × 1: full cyan opaque, then 100% K at half alpha (premultiplied: K 128, alpha 128). - let mut file = Cursor::new(Vec::new()); - let mut enc = TiffEncoder::new(&mut file).unwrap(); - let mut img = enc.new_image::(2, 1).unwrap(); - img.encoder().write_tag(tiff::tags::Tag::ExtraSamples, &[1u16][..]).unwrap(); - img.write_data(&[255, 0, 0, 0, 255, 0, 0, 0, 128, 128]).unwrap(); - let bytes = file.into_inner(); + let bytes = test_extra_tiff_u8(2, 1, 5, 5, 1, &[255, 0, 0, 0, 255, 0, 0, 0, 128, 128]); let naive = |[c, m, y, k]: [f32; 4]| [(1.0 - c) * (1.0 - k), (1.0 - m) * (1.0 - k), (1.0 - y) * (1.0 - k)]; let px = extra_samples_tiff_rgba(&bytes, naive).expect("CMYKA reads"); assert_eq!(px.dimensions(), (2, 1)); @@ -764,31 +827,12 @@ mod tests { assert!(extra_samples_tiff_rgba(&ImageBlob::cmyk_tiff(&inks()).unwrap().bytes, naive).is_none()); } - /// Two 8-bit samples a pixel: gray and one extra sample, which the file's `ExtraSamples` names. - struct GrayExtra8; - impl tiff::encoder::colortype::ColorType for GrayExtra8 { - type Inner = u8; - const TIFF_VALUE: tiff::tags::PhotometricInterpretation = tiff::tags::PhotometricInterpretation::BlackIsZero; - const BITS_PER_SAMPLE: &'static [u16] = &[8, 8]; - const SAMPLE_FORMAT: &'static [tiff::tags::SampleFormat] = &[tiff::tags::SampleFormat::Uint; 2]; - fn horizontal_predict(row: &[u8], result: &mut Vec) { - result.extend_from_slice(row); - } - } - - /// A grayscale TIFF with an alpha channel, or with a channel that isn't one (#1466): the image - /// decoder reads neither. + /// A grayscale TIFF with an alpha channel, or with a channel that isn't one (#1466). #[test] fn a_grayscale_tiff_with_an_extra_channel_reads_as_rgba() { let gray = |extra: u16| { - let mut file = Cursor::new(Vec::new()); - let mut enc = tiff::encoder::TiffEncoder::new(&mut file).unwrap(); - let mut img = enc.new_image::(3, 1).unwrap(); - img.encoder().write_tag(tiff::tags::Tag::ExtraSamples, &[extra][..]).unwrap(); // White opaque, a gray of 64 at 80% alpha (premultiplied: 51), black with no alpha. - img.write_data(&[255, 255, 51, 204, 0, 0]).unwrap(); - let bytes = file.into_inner(); - assert!(image::load_from_memory(&bytes).is_err(), "the image decoder reads it now: this reader may go"); + let bytes = test_extra_tiff_u8(3, 1, 1, 2, extra, &[255, 255, 51, 204, 0, 0]); extra_samples_tiff_rgba(&bytes, |_| [0.0; 3]).expect("gray with an extra sample reads").into_raw() }; assert_eq!(gray(1), [255, 255, 255, 255, 64, 64, 64, 204, 0, 0, 0, 0], "associated alpha, divided back out"); @@ -796,48 +840,15 @@ mod tests { assert_eq!(gray(0), [255, 255, 255, 255, 51, 51, 51, 255, 0, 0, 0, 255], "a channel that isn't alpha: opaque"); } - /// Five 16-bit samples a pixel: the four inks and one extra sample, which the file's - /// `ExtraSamples` names. - struct Cmyka16; - impl tiff::encoder::colortype::ColorType for Cmyka16 { - type Inner = u16; - const TIFF_VALUE: tiff::tags::PhotometricInterpretation = tiff::tags::PhotometricInterpretation::CMYK; - const BITS_PER_SAMPLE: &'static [u16] = &[16; 5]; - const SAMPLE_FORMAT: &'static [tiff::tags::SampleFormat] = &[tiff::tags::SampleFormat::Uint; 5]; - fn horizontal_predict(row: &[u16], result: &mut Vec) { - result.extend_from_slice(row); - } - } - - /// Two 16-bit samples a pixel: gray and one extra sample. - struct GrayExtra16; - impl tiff::encoder::colortype::ColorType for GrayExtra16 { - type Inner = u16; - const TIFF_VALUE: tiff::tags::PhotometricInterpretation = tiff::tags::PhotometricInterpretation::BlackIsZero; - const BITS_PER_SAMPLE: &'static [u16] = &[16, 16]; - const SAMPLE_FORMAT: &'static [tiff::tags::SampleFormat] = &[tiff::tags::SampleFormat::Uint; 2]; - fn horizontal_predict(row: &[u16], result: &mut Vec) { - result.extend_from_slice(row); - } - } - - /// A one-row TIFF of `C`'s pixels `data`, with the ExtraSamples value `extra`. - fn extra_tiff>(extra: u16, data: &[u16]) -> Vec { - let samples = C::BITS_PER_SAMPLE.len(); - let mut file = Cursor::new(Vec::new()); - let mut enc = tiff::encoder::TiffEncoder::new(&mut file).unwrap(); - let mut img = enc.new_image::(u32::try_from(data.len() / samples).unwrap(), 1).unwrap(); - img.encoder().write_tag(tiff::tags::Tag::ExtraSamples, &[extra][..]).unwrap(); - img.write_data(data).unwrap(); - file.into_inner() - } - /// 16-bit CMYK with alpha converts its 16-bit inks and alpha, and rounds only the result to 8 /// bits; the high byte of each sample alone would give other pixels. #[test] fn a_16_bit_cmyk_tiff_with_alpha_converts_at_16_bits() { let naive = |[c, m, y, k]: [f32; 4]| [(1.0 - c) * (1.0 - k), (1.0 - m) * (1.0 - k), (1.0 - y) * (1.0 - k)]; - let read = |extra: u16, data: &[u16]| extra_samples_tiff_rgba(&extra_tiff::(extra, data), naive).expect("CMYKA reads").into_raw(); + let read = |extra: u16, data: &[u16]| { + let w = u32::try_from(data.len() / 5).unwrap(); + extra_samples_tiff_rgba(&test_extra_tiff_u16(w, 1, 5, 5, extra, data), naive).expect("CMYKA reads").into_raw() + }; // Unassociated: 129 of cyan, opaque; no ink at an alpha of 129; no ink at an alpha of 386. let straight = [129, 0, 0, 0, 65535, 0, 0, 0, 0, 129, 0, 0, 0, 0, 386]; assert_eq!(read(2, &straight), [254, 255, 255, 255, 255, 255, 255, 1, 255, 255, 255, 2]); @@ -851,7 +862,7 @@ mod tests { fn a_16_bit_grayscale_tiff_with_alpha_converts_at_16_bits() { let read = |extra: u16| { // A gray of 129, opaque, then 128 at an alpha of 256. - let bytes = extra_tiff::(extra, &[129, 65535, 128, 256]); + let bytes = test_extra_tiff_u16(2, 1, 1, 2, extra, &[129, 65535, 128, 256]); extra_samples_tiff_rgba(&bytes, |_| [0.0; 3]).expect("gray with alpha reads").into_raw() }; assert_eq!(read(2), [1, 1, 1, 255, 0, 0, 0, 1], "unassociated"); @@ -862,16 +873,11 @@ mod tests { /// Alpha Handling), whatever its color samples hold. #[test] fn a_pixel_with_no_associated_alpha_has_no_color() { - use tiff::encoder::{TiffEncoder, colortype::CMYKA8}; let naive = |[c, m, y, k]: [f32; 4]| [(1.0 - c) * (1.0 - k), (1.0 - m) * (1.0 - k), (1.0 - y) * (1.0 - k)]; - let mut file = Cursor::new(Vec::new()); - let mut enc = TiffEncoder::new(&mut file).unwrap(); - let mut img = enc.new_image::(1, 1).unwrap(); - img.encoder().write_tag(tiff::tags::Tag::ExtraSamples, &[1u16][..]).unwrap(); - img.write_data(&[255, 0, 0, 0, 0]).unwrap(); - let cmyk = extra_samples_tiff_rgba(&file.into_inner(), naive).expect("CMYKA reads"); + let cmyk_bytes = test_extra_tiff_u8(1, 1, 5, 5, 1, &[255, 0, 0, 0, 0]); + let cmyk = extra_samples_tiff_rgba(&cmyk_bytes, naive).expect("CMYKA reads"); assert_eq!(cmyk.into_raw(), [255, 255, 255, 0], "no ink"); - let gray = extra_samples_tiff_rgba(&extra_tiff::(1, &[50_000, 0]), |_| [0.0; 3]).expect("gray reads"); + let gray = extra_samples_tiff_rgba(&test_extra_tiff_u16(1, 1, 1, 2, 1, &[50_000, 0]), |_| [0.0; 3]).expect("gray reads"); assert_eq!(gray.into_raw(), [0, 0, 0, 0], "a gray of zero"); } @@ -944,8 +950,8 @@ mod tests { assert!(b.is_cmyk()); assert_eq!(b.cmyk(), Some(inks()), "lossless"); // Every image reader sees an RGB image: cyan is (0, 255, 255). - let rgb = image::load_from_memory(&b.bytes).unwrap().to_rgb8(); - assert_eq!(rgb.get_pixel(1, 0).0, [0, 255, 255]); + let rgb = craft_image_codecs::decode(&b.bytes).unwrap().to_rgba8(); + assert_eq!(&rgb[4..7], &[0, 255, 255]); } #[test] @@ -975,8 +981,11 @@ mod tests { assert!(big.is_cmyk()); assert_eq!(big.header_size(), Some((6000, 6000))); assert_eq!(big.cmyk(), None); - let mut png = Vec::new(); - image::RgbaImage::new(2, 2).write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let png = craft_image_codecs::encode( + &CodecImage::from_raw(2, Format::Png, 2, ChannelLayout::Rgba, SampleType::U8, vec![0; 16]).unwrap(), + &EncodeOptions::default(), + ) + .unwrap(); assert_eq!(ImageBlob::png(png).header_size(), None, "not a JPEG or TIFF"); } @@ -989,8 +998,11 @@ mod tests { // 3 × 3 around (1, 0), clipped to the image: all six pixels averaged. assert_eq!(b.sample_cmyk_object(1.5, 0.5, (3, 2), 3), Some([45, 55, 69, 56])); assert_eq!(b.sample_cmyk_object(3.5, 0.5, (3, 2), 1), None, "outside"); - let mut png = Vec::new(); - image::RgbaImage::new(2, 2).write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let png = craft_image_codecs::encode( + &CodecImage::from_raw(2, Format::Png, 2, ChannelLayout::Rgba, SampleType::U8, vec![0; 16]).unwrap(), + &EncodeOptions::default(), + ) + .unwrap(); assert_eq!(ImageBlob::png(png).sample_cmyk_object(0.5, 0.5, (2, 2), 1), None, "an RGB image has no inks"); } @@ -999,8 +1011,11 @@ mod tests { // A flat CMYK JPEG: Adobe's inverted samples with its marker. let flat = [10u8, 40, 100, 20]; let px: Vec = (0..16 * 16).flat_map(|_| flat).collect(); - let mut jpg = Vec::new(); - jpeg_encoder::Encoder::new(&mut jpg, 100).encode(&px, 16, 16, jpeg_encoder::ColorType::Cmyk).unwrap(); + let jpg = craft_image_codecs::encode( + &CodecImage::from_raw(16, Format::Jpeg, 16, ChannelLayout::Cmyk, SampleType::U8, px).unwrap(), + &EncodeOptions { jpeg_quality: 100, ..EncodeOptions::default() }, + ) + .unwrap(); let b = ImageBlob::new("image/jpeg", jpg); assert_eq!(jpeg_components(&b.bytes), Some(4)); assert!(b.is_cmyk()); @@ -1013,10 +1028,16 @@ mod tests { #[test] fn other_images_are_not_cmyk() { - let mut png = Vec::new(); - image::RgbaImage::new(2, 2).write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); - let mut jpg = Vec::new(); - image::RgbImage::new(8, 8).write_to(&mut Cursor::new(&mut jpg), image::ImageFormat::Jpeg).unwrap(); + let png = craft_image_codecs::encode( + &CodecImage::from_raw(2, Format::Png, 2, ChannelLayout::Rgba, SampleType::U8, vec![0; 16]).unwrap(), + &EncodeOptions::default(), + ) + .unwrap(); + let jpg = craft_image_codecs::encode( + &CodecImage::from_raw(8, Format::Jpeg, 8, ChannelLayout::Rgb, SampleType::U8, vec![0; 8 * 8 * 3]).unwrap(), + &EncodeOptions::default(), + ) + .unwrap(); for b in [ImageBlob::png(png), ImageBlob::new("image/jpeg", jpg), ImageBlob::new("image/tiff", b"II*\0junk".to_vec())] { assert!(!b.is_cmyk() && b.cmyk().is_none(), "{}", b.mime); } diff --git a/crates/doc/src/links.rs b/crates/doc/src/links.rs index 80740b7cc2..2d9c31a910 100644 --- a/crates/doc/src/links.rs +++ b/crates/doc/src/links.rs @@ -156,19 +156,15 @@ impl ImageBlob { /// decoded none (an image past the allowance). pub fn checked_with_pixels(mut self, proxy: bool) -> Option<(Self, Option)> { let max = crate::MAX_RASTER_ALLOC; - let reader = || image::ImageReader::new(Cursor::new(self.bytes.as_slice())).with_guessed_format().ok(); - let (w, h) = reader()?.into_dimensions().ok()?; + let info = craft_image_codecs::probe(&self.bytes).ok()?; + let (w, h) = (info.width, info.height); if u64::from(w) * u64::from(h) > max / 4 { return Some((self, None)); } - let mut r = reader()?; - let mut limits = image::Limits::default(); - limits.max_alloc = Some(max); - r.limits(limits); - let img = match r.decode() { + let img = match decode_dynamic(&self.bytes, max) { Ok(img) => img, - Err(image::ImageError::Limits(_)) => return Some((self, None)), - Err(_) => return None, + Err(true) => return Some((self, None)), + Err(false) => return None, }; if proxy && self.proxy.is_none() && w.max(h) > PROXY_SIZE { self.proxy = proxy_of(&img).map(Arc::new); @@ -197,20 +193,49 @@ pub const MISSING_SIDE: u32 = 64; /// it can't be encoded. pub fn missing_placeholder() -> Option> { let last = MISSING_SIDE - 1; - let img = image::RgbaImage::from_fn(MISSING_SIDE, MISSING_SIDE, |x, y| { - let edge = x == 0 || y == 0 || x == last || y == last; - let cross = x.abs_diff(y) <= 1 || (x + y).abs_diff(last) <= 1; - image::Rgba(if edge || cross { [200, 60, 60, 255] } else { [236, 236, 236, 255] }) - }); - let mut png = Vec::new(); - img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?; - Some(png) + let mut raw = Vec::with_capacity((MISSING_SIDE * MISSING_SIDE * 4) as usize); + for y in 0..MISSING_SIDE { + for x in 0..MISSING_SIDE { + let edge = x == 0 || y == 0 || x == last || y == last; + let cross = x.abs_diff(y) <= 1 || (x + y).abs_diff(last) <= 1; + raw.extend_from_slice(if edge || cross { &[200, 60, 60, 255] } else { &[236, 236, 236, 255] }); + } + } + let img = craft_image_codecs::Image::from_raw( + MISSING_SIDE, + MISSING_SIDE, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + raw, + ) + .ok()?; + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok() +} + +fn decode_dynamic(bytes: &[u8], max_alloc: u64) -> Result { + use craft_image_codecs::{ChannelLayout, CodecError, DecodeOptions, Limits, SampleType}; + let opts = DecodeOptions { limits: Limits { max_alloc: Some(max_alloc), ..Limits::default() }, ..DecodeOptions::default() }; + let img = craft_image_codecs::decode_with(bytes, &opts).map_err(|e| matches!(e, CodecError::LimitExceeded(_)))?; + let (w, h) = img.dimensions(); + match (img.layout(), img.sample_type()) { + (ChannelLayout::Gray, SampleType::U8) => image::GrayImage::from_raw(w, h, img.into_data()).map(image::DynamicImage::ImageLuma8), + (ChannelLayout::GrayA, SampleType::U8) => image::GrayAlphaImage::from_raw(w, h, img.into_data()).map(image::DynamicImage::ImageLumaA8), + (ChannelLayout::Rgb, SampleType::U8) => image::RgbImage::from_raw(w, h, img.into_data()).map(image::DynamicImage::ImageRgb8), + (ChannelLayout::Rgba, SampleType::U8) => image::RgbaImage::from_raw(w, h, img.into_data()).map(image::DynamicImage::ImageRgba8), + (ChannelLayout::Gray, SampleType::U16) => image::ImageBuffer::from_raw(w, h, img.to_u16_samples()?).map(image::DynamicImage::ImageLuma16), + (ChannelLayout::GrayA, SampleType::U16) => image::ImageBuffer::from_raw(w, h, img.to_u16_samples()?).map(image::DynamicImage::ImageLumaA16), + (ChannelLayout::Rgb, SampleType::U16) => image::ImageBuffer::from_raw(w, h, img.to_u16_samples()?).map(image::DynamicImage::ImageRgb16), + (ChannelLayout::Rgba, SampleType::U16) => image::ImageBuffer::from_raw(w, h, img.to_u16_samples()?).map(image::DynamicImage::ImageRgba16), + _ => None, + } + .ok_or(false) } /// `bytes` decoded and shrunk to fit [`PROXY_SIZE`] as a PNG; `None` when small enough already or /// undecodable. fn proxy_png(bytes: &[u8]) -> Option> { - let (w, h) = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_dimensions().ok()?; + let info = craft_image_codecs::probe(bytes).ok()?; + let (w, h) = (info.width, info.height); if w.max(h) <= PROXY_SIZE { return None; } @@ -220,20 +245,17 @@ fn proxy_png(bytes: &[u8]) -> Option> { if u64::from(w) * u64::from(h) > crate::MAX_RASTER_ALLOC / 4 { return None; } - let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?; - let mut limits = image::Limits::default(); - limits.max_alloc = Some(crate::MAX_RASTER_ALLOC); - reader.limits(limits); - proxy_of(&reader.decode().ok()?) + proxy_of(&decode_dynamic(bytes, crate::MAX_RASTER_ALLOC).ok()?) } /// Decoded image `img` shrunk to fit [`PROXY_SIZE`] as a PNG. fn proxy_of(img: &image::DynamicImage) -> Option> { + use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType}; let (w, h) = crate::resample::fit_size(img.width(), img.height(), PROXY_SIZE, PROXY_SIZE); let small = crate::resample::averaged(img, w, h); - let mut png = Vec::new(); - small.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?; - Some(png) + let (sw, sh) = small.dimensions(); + let img = Image::from_raw(sw, sh, ChannelLayout::Rgba, SampleType::U8, small.into_raw()).ok()?; + craft_image_codecs::encode(&img, Format::Png, &EncodeOptions::default()).ok() } /// `n` and every descendant, opacity-mask art included. @@ -527,7 +549,41 @@ mod tests { fn png(w: u32, h: u32) -> Vec { let mut out = vec![]; - image::RgbaImage::from_pixel(w, h, image::Rgba([10, 200, 30, 255])).write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(w, h, image::Rgba([10, 200, 30, 255]))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); out } @@ -590,7 +646,27 @@ mod tests { #[test] fn the_placeholder_is_a_png() { let png = missing_placeholder().unwrap(); - assert_eq!(image::load_from_memory(&png).unwrap().width(), MISSING_SIDE); + assert_eq!( + craft_image_codecs::decode(&png) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .width(), + MISSING_SIDE + ); } #[test] @@ -651,7 +727,23 @@ mod tests { #[test] fn large_images_get_a_small_png_preview() { let big = ImageBlob::new("image/png", png(600, 300)).with_proxy(); - let p = image::load_from_memory(big.proxy.as_ref().unwrap()).unwrap(); + let p = craft_image_codecs::decode(big.proxy.as_ref().unwrap()) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap(); assert_eq!((p.width(), p.height()), (256, 128)); assert!(!big.is_proxy(), "the bytes are the full image"); assert!(ImageBlob::new("image/png", png(40, 20)).with_proxy().proxy.is_none(), "small images keep their pixels"); @@ -664,12 +756,28 @@ mod tests { fn a_checked_image_is_refused_when_its_pixels_cant_be_read() { let full = png(600, 300); let big = ImageBlob::new("image/png", full.clone()).checked_with_proxy(true).unwrap(); - let p = image::load_from_memory(big.proxy.as_ref().unwrap()).unwrap(); + let p = craft_image_codecs::decode(big.proxy.as_ref().unwrap()) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap(); assert_eq!((p.width(), p.height()), (256, 128)); assert!(ImageBlob::new("image/png", full.clone()).checked_with_proxy(false).unwrap().proxy.is_none(), "no preview asked for"); assert!(ImageBlob::new("image/png", png(40, 20)).checked_with_proxy(true).unwrap().proxy.is_none(), "small images keep their pixels"); let cut = full[..full.len() / 2].to_vec(); - assert_eq!(image::ImageReader::new(Cursor::new(&cut)).with_guessed_format().unwrap().into_dimensions().unwrap(), (600, 300)); + assert_eq!(craft_image_codecs::decode(&cut).unwrap().dimensions(), (600, 300)); assert!(ImageBlob::new("image/png", cut).checked_with_proxy(true).is_none(), "cut to half its length"); assert!(ImageBlob::new("image/png", vec![1, 2, 3]).checked_with_proxy(false).is_none(), "not an image"); } @@ -680,7 +788,29 @@ mod tests { let full = png(600, 300); let (blob, pixels) = ImageBlob::new("image/png", full.clone()).checked_with_pixels(true).unwrap(); assert!(blob.proxy.is_some(), "the preview is made as checked_with_proxy makes it"); - assert_eq!(pixels.map(|p| p.to_rgba8()), Some(image::load_from_memory(&full).unwrap().to_rgba8())); + assert_eq!( + pixels.map(|p| p.to_rgba8()), + Some( + craft_image_codecs::decode(&full) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() + ) + ); } /// PNG CRC-32 (the same polynomial ZIP uses), so a hand-written header is one a decoder accepts. @@ -739,11 +869,62 @@ mod tests { #[test] fn a_preview_keeps_the_color_beside_clear_pixels() { let mut full = vec![]; - image::RgbaImage::from_fn(1024, 4, |x, _| if x % 2 == 0 { image::Rgba([200, 30, 30, 255]) } else { image::Rgba([0, 0, 0, 0]) }) - .write_to(&mut Cursor::new(&mut full), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = + (image::RgbaImage::from_fn(1024, 4, |x, _| if x % 2 == 0 { image::Rgba([200, 30, 30, 255]) } else { image::Rgba([0, 0, 0, 0]) })) + .into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| full.extend_from_slice(&__b)) + } + .unwrap(); for blob in [ImageBlob::png(full.clone()).with_proxy(), ImageBlob::png(full.clone()).checked_with_proxy(true).unwrap()] { - let p = image::load_from_memory(blob.proxy.as_ref().unwrap()).unwrap().into_rgba8(); + let p = craft_image_codecs::decode(blob.proxy.as_ref().unwrap()) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .into_rgba8(); assert_eq!(p.dimensions(), (PROXY_SIZE, 1)); assert!(p.pixels().all(|q| q.0 == [200, 30, 30, 128]), "{:?}", p.get_pixel(0, 0)); } diff --git a/crates/doc/src/pixels.rs b/crates/doc/src/pixels.rs index c451fea7be..e23023e34e 100644 --- a/crates/doc/src/pixels.rs +++ b/crates/doc/src/pixels.rs @@ -20,15 +20,15 @@ pub type PixelPick<'a> = (Option<[f64; 4]>, usize, &'a dyn Fn(f64, f64) -> bool) /// the header first: the decoder's limit is on the file's samples, and a gray image is a quarter /// of what it becomes here (#1717). fn rgba_within(bytes: &[u8], max: u64) -> Option { - let (w, h) = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_dimensions().ok()?; + let mut opts = craft_image_codecs::DecodeOptions::default(); + opts.limits.max_pixels = max / 4; + opts.limits.max_alloc = max; + let img = craft_image_codecs::decode_with(bytes, &opts).ok()?; + let (w, h) = img.dimensions(); if u64::from(w) * u64::from(h) > max / 4 { return None; } - let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?; - let mut limits = image::Limits::default(); - limits.max_alloc = Some(max); - reader.limits(limits); - Some(reader.decode().ok()?.into_rgba8()) + image::RgbaImage::from_raw(w, h, img.to_rgba8()) } impl ImageBlob { @@ -60,8 +60,15 @@ impl ImageBlob { if !changed { return None; } - let mut png = Vec::new(); - img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?; + let raw = craft_image_codecs::Image::from_raw( + img.width(), + img.height(), + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + img.into_raw(), + ) + .ok()?; + let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; Some(Self::png(png)) } @@ -129,14 +136,13 @@ impl ImageBlob { if !changed { return None; } - let mut png = Vec::new(); - let mut out = Cursor::new(&mut png); - if opaque { - let levels = gray_alpha.iter().step_by(2).copied().collect(); - image::GrayImage::from_raw(width, height, levels)?.write_to(&mut out, image::ImageFormat::Png).ok()?; + let (layout, data) = if opaque { + (craft_image_codecs::ChannelLayout::Gray, gray_alpha.iter().step_by(2).copied().collect()) } else { - image::GrayAlphaImage::from_raw(width, height, gray_alpha)?.write_to(&mut out, image::ImageFormat::Png).ok()?; - } + (craft_image_codecs::ChannelLayout::GrayA, gray_alpha) + }; + let raw = craft_image_codecs::Image::from_raw(width, height, layout, craft_image_codecs::SampleType::U8, data).ok()?; + let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; Some(Self::png(png)) } } @@ -156,23 +162,28 @@ impl ImageBlob { /// header. pub fn gray_source(&self) -> Option { let gray = |one_bit: bool, alpha: bool| Some(GraySource { one_bit, alpha }); - if let Some((kind, _)) = crate::cmyk::tiff(&self.bytes) { - return match kind { - tiff::ColorType::Gray(bits) => gray(bits == 1, false), - tiff::ColorType::GrayA(bits) => gray(bits == 1, true), + if let Some(info) = crate::cmyk::tiff_image_info(&self.bytes) { + return match (info.photometric, info.samples_per_pixel, info.bits_per_sample.first().copied()) { + (0 | 1, 1, Some(bits)) => gray(bits == 1, false), + (0 | 1, 2, Some(bits)) => gray(bits == 1, true), _ => None, }; } if crate::cmyk::jpeg_components(&self.bytes) == Some(1) { return gray(false, false); } - use image::{ExtendedColorType as E, ImageDecoder as _}; - let reader = image::ImageReader::new(Cursor::new(self.bytes.as_slice())).with_guessed_format().ok()?; - match reader.into_decoder().ok()?.original_color_type() { - E::L1 => gray(true, false), - E::La1 => gray(true, true), - E::L2 | E::L4 | E::L8 | E::L16 => gray(false, false), - E::La2 | E::La4 | E::La8 | E::La16 => gray(false, true), + if self.bytes.starts_with(b"\x89PNG\r\n\x1a\n") && self.bytes.get(12..16) == Some(b"IHDR".as_slice()) { + let depth = self.bytes.get(24).copied()?; + let color = self.bytes.get(25).copied()?; + return match color { + 0 => gray(depth == 1, false), + 4 => gray(depth == 1, true), + _ => None, + }; + } + match craft_image_codecs::decode(&self.bytes).ok()?.layout() { + craft_image_codecs::ChannelLayout::Gray => gray(false, false), + craft_image_codecs::ChannelLayout::GrayA => gray(false, true), _ => None, } } @@ -206,7 +217,10 @@ impl ImageBlob { /// The width and height in pixels the image's file says it has; `None` for data that isn't an /// image the decoder reads. Reads only its header. pub fn pixel_size(&self) -> Option<(u32, u32)> { - image::ImageReader::new(Cursor::new(self.bytes.as_slice())).with_guessed_format().ok()?.into_dimensions().ok() + craft_image_codecs::probe_size(&self.bytes) + .ok() + .or_else(|| self.header_size()) + .or_else(|| craft_image_codecs::decode(&self.bytes).ok().map(|i| i.dimensions())) } /// Whether the image's file is a PNG that stores palette indices (an indexed-color image). @@ -350,12 +364,66 @@ mod tests { fn blob(px: &[[u8; 4]], w: u32, h: u32) -> ImageBlob { let img = image::RgbaImage::from_raw(w, h, px.concat()).unwrap(); let mut png = Vec::new(); - img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); ImageBlob::png(png) } fn pixels(b: &ImageBlob) -> Vec<[u8; 4]> { - image::load_from_memory(&b.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect() + craft_image_codecs::decode(&b.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() + .pixels() + .map(|p| p.0) + .collect() } /// Sampling reads the pixels of a box of the image, spread to about the budget, and only those @@ -420,7 +488,41 @@ mod tests { fn pixels_past_the_allowance_are_not_decoded() { let grey = image::GrayImage::from_raw(4, 2, vec![7; 8]).unwrap(); let mut png = Vec::new(); - grey.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (grey).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); assert!(rgba_within(&png, 31).is_none(), "8 grey bytes are 32 as RGBA"); assert_eq!(rgba_within(&png, 32).map(|i| i.dimensions()), Some((4, 2))); assert!(rgba_within(b"not an image", u64::MAX).is_none()); @@ -454,7 +556,41 @@ mod tests { assert!(rgba_within(&huge, u64::MAX).is_none()); let gray = image::GrayImage::from_raw(4, 2, vec![7; 8]).unwrap(); let mut png = Vec::new(); - gray.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (gray).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); assert_eq!(rgba_within(&png, 35).map(|i| i.dimensions()), Some((4, 2)), "32 bytes as RGBA, within 35"); } @@ -527,7 +663,41 @@ mod tests { fn png_of(img: image::DynamicImage) -> ImageBlob { let mut png = Vec::new(); - img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); ImageBlob::png(png) } @@ -538,8 +708,19 @@ mod tests { assert_eq!(l8.gray_source(), gray(false, false)); let la8 = png_of(image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(1, 1, vec![0, 128]).unwrap())); assert_eq!(la8.gray_source(), gray(false, true)); - let mut jpeg = Vec::new(); - jpeg_encoder::Encoder::new(&mut jpeg, 90).encode(&[0, 255, 0, 255], 2, 2, jpeg_encoder::ColorType::Luma).unwrap(); + let jpeg = craft_image_codecs::encode( + &craft_image_codecs::Image::from_raw( + 2, + craft_image_codecs::Format::Jpeg, + 2, + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U8, + vec![0, 255, 0, 255], + ) + .unwrap(), + &craft_image_codecs::EncodeOptions { jpeg_quality: 90, ..craft_image_codecs::EncodeOptions::default() }, + ) + .unwrap(); assert_eq!(ImageBlob::new("image/jpeg", jpeg).gray_source(), gray(false, false)); // Black, white; white, black. let tif = ImageBlob::new("image/tiff", bilevel_tiff(2, 2, &[0b0100_0000, 0b1000_0000])); diff --git a/crates/doc/src/placed_document.rs b/crates/doc/src/placed_document.rs index cd423658d7..d762576120 100644 --- a/crates/doc/src/placed_document.rs +++ b/crates/doc/src/placed_document.rs @@ -347,7 +347,7 @@ pub fn full_bytes(p: &PlacedDocument, blob: &ImageBlob) -> Option>> /// The size in pixels of image bytes `bytes` (a preview), read from its header. pub fn image_size(bytes: &[u8]) -> Option<(u32, u32)> { - image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?.into_dimensions().ok() + craft_image_codecs::probe(bytes).ok().map(|i| (i.width, i.height)) } // ---------- reading files ---------- @@ -798,9 +798,41 @@ mod tests { fn a_file_that_cant_be_read_shows_its_preview() { set_loader(stub_loader); let mut png = vec![]; - image::RgbaImage::from_pixel(8, 4, image::Rgba([0, 200, 0, 255])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(8, 4, image::Rgba([0, 200, 0, 255]))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let mut blob = ImageBlob::new("image/png", png); blob.proxy = Some(blob.bytes.clone()); let mut d = Document::new(200.0, 200.0); diff --git a/crates/doc/src/separated.rs b/crates/doc/src/separated.rs index 8eb7cefe66..8308801b24 100644 --- a/crates/doc/src/separated.rs +++ b/crates/doc/src/separated.rs @@ -181,9 +181,15 @@ impl Separated { /// prints; `None` when it can't be written. pub fn plate_png(&self, plate: &str, own: &dyn Fn(&str) -> bool, equivalent: &dyn Fn(&InkPlate) -> [f32; 4]) -> Option { let gray: Vec = self.coverage_as(plate, own, equivalent).into_iter().map(|v| 255 - v).collect(); - let img = image::GrayImage::from_raw(self.width, self.height, gray)?; - let mut png = Vec::new(); - img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?; + let img = craft_image_codecs::Image::from_raw( + self.width, + self.height, + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U8, + gray, + ) + .ok()?; + let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; Some(ImageBlob::png(png)) } @@ -258,34 +264,61 @@ impl ImageBlob { /// [`Self::separated_tiff`], noting `clip` too, the clipping path its file draws it through, in /// its pixel space ([`Self::separated_clip`]). pub fn separated_tiff_clipped(s: &Separated, ppi: Option<(f64, f64)>, files: &[PlateFile], clip: Option<&PathData>) -> Option { - use tiff::encoder::{Compression, Rational, TiffEncoder, colortype, compression::DeflateLevel}; - use tiff::tags::{ResolutionUnit, Tag}; + use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value, tags}; + use flate2::{Compression, write::ZlibEncoder}; + use std::io::Write as _; let ppi = ppi.filter(|(x, y)| [x, y].iter().all(|v| v.is_finite() && **v > 0.0)); - // Ten-thousandths of a pixel per inch. - let r = |v: f64| Rational { n: (v * 10_000.0).round() as u32, d: 10_000 }; - let mut out = Cursor::new(Vec::new()); - let mut enc = TiffEncoder::new(&mut out).ok()?.with_compression(Compression::Deflate(DeflateLevel::Balanced)); - let mut img = enc.new_image::(s.width, s.height).ok()?; + let deflate = |raw: &[u8]| -> Option> { + let mut enc = ZlibEncoder::new(Vec::new(), Compression::default()); + enc.write_all(raw).ok()?; + enc.finish().ok() + }; + let mut ifds = Vec::with_capacity(1 + s.plates.len()); + let mut comp_ifd = IfdBuilder::new(); + comp_ifd + .set(tags::IMAGE_WIDTH, Value::Long(vec![s.width])) + .set(tags::IMAGE_LENGTH, Value::Long(vec![s.height])) + .set(tags::BITS_PER_SAMPLE, Value::Short(vec![8; 4])) + .set(tags::COMPRESSION, Value::Short(vec![8])) + .set(tags::PHOTOMETRIC, Value::Short(vec![5])) + .set(tags::SAMPLES_PER_PIXEL, Value::Short(vec![4])) + .set(tags::PLANAR_CONFIGURATION, Value::Short(vec![1])) + .set(tags::SAMPLE_FORMAT, Value::Short(vec![1; 4])) + .set_image(ImageData::Strips { rows_per_strip: s.height.max(1), strips: vec![deflate(&s.composite().data)?] }); if let Some((x, y)) = ppi { - img.encoder().write_tag(Tag::XResolution, r(x)).ok()?; - img.encoder().write_tag(Tag::YResolution, r(y)).ok()?; - img.encoder().write_tag(Tag::ResolutionUnit, ResolutionUnit::Inch).ok()?; + // Ten-thousandths of a pixel per inch. + let r = |v: f64| ((v * 10_000.0).round() as u32, 10_000); + comp_ifd + .set(tags::X_RESOLUTION, Value::Rational(vec![r(x)])) + .set(tags::Y_RESOLUTION, Value::Rational(vec![r(y)])) + .set(tags::RESOLUTION_UNIT, Value::Short(vec![2])); } // One line for the plate files, one for the clipping path. let lines: Vec = [(!files.is_empty()).then(|| files_description(files)), clip.and_then(clip_description)].into_iter().flatten().collect(); if !lines.is_empty() { - img.encoder().write_tag(Tag::ImageDescription, lines.join("\n").as_str()).ok()?; + comp_ifd.set(tags::IMAGE_DESCRIPTION, Value::Ascii(lines.join("\n"))); } - img.write_data(&s.composite().data).ok()?; + ifds.push(comp_ifd); for p in &s.plates { // White is no ink, so a viewer that shows a plate shows it as it prints. - let mut img = enc.new_image::(s.width, s.height).ok()?; - img.encoder().write_tag(Tag::ImageDescription, description(p).as_str()).ok()?; let inverted: Vec = p.data.iter().map(|v| 255 - v).collect(); - img.write_data(&inverted).ok()?; + let mut p_ifd = IfdBuilder::new(); + p_ifd + .set(tags::IMAGE_WIDTH, Value::Long(vec![s.width])) + .set(tags::IMAGE_LENGTH, Value::Long(vec![s.height])) + .set(tags::BITS_PER_SAMPLE, Value::Short(vec![8])) + .set(tags::COMPRESSION, Value::Short(vec![8])) + .set(tags::PHOTOMETRIC, Value::Short(vec![1])) + .set(tags::SAMPLES_PER_PIXEL, Value::Short(vec![1])) + .set(tags::PLANAR_CONFIGURATION, Value::Short(vec![1])) + .set(tags::SAMPLE_FORMAT, Value::Short(vec![1])) + .set(tags::IMAGE_DESCRIPTION, Value::Ascii(description(p))) + .set_image(ImageData::Strips { rows_per_strip: s.height.max(1), strips: vec![deflate(&inverted)?] }); + ifds.push(p_ifd); } - Some(Self::new("image/tiff", out.into_inner())) + let bytes = TiffWriter::new(ByteOrder::Little, false).write(&ifds).ok()?; + Some(Self::new("image/tiff", bytes)) } /// Does the image hold plates ([`ImageBlob::separated_tiff`]), at most [`MAX_PLATES`] of them? @@ -293,14 +326,13 @@ impl ImageBlob { /// CMYK image of its composite only, as [`Self::separated`] refuses it. Reads only the TIFF's /// directories, at most [`MAX_DIRECTORIES`]. pub fn is_separated(&self) -> bool { - let Some((_, mut d)) = crate::cmyk::tiff(&self.bytes) else { return false }; - let (mut plates, mut directories) = (0usize, 1usize); - while d.more_images() { - directories += 1; - if directories > MAX_DIRECTORIES || d.next_image().is_err() { - return false; - } - if d.get_tag_ascii_string(tiff::tags::Tag::ImageDescription).ok().is_some_and(|s| s.starts_with(MARK)) { + let Some(tiff) = crate::cmyk::parse_tiff(&self.bytes) else { return false }; + if tiff.ifds.len() > MAX_DIRECTORIES { + return false; + } + let mut plates = 0usize; + for ifd in tiff.ifds.iter().skip(1) { + if ifd.string(craft_tiff::tags::IMAGE_DESCRIPTION).is_some_and(|s| s.starts_with(MARK)) { plates += 1; if plates > MAX_PLATES { return false; @@ -313,16 +345,16 @@ impl ImageBlob { /// The plate files of their own a separated image was read from, as they were then; none for /// other images. Reads only the TIFF's first directory. pub fn plate_files(&self) -> Vec { - let Some((_, mut d)) = crate::cmyk::tiff(&self.bytes) else { return vec![] }; - d.get_tag_ascii_string(tiff::tags::Tag::ImageDescription).ok().as_deref().map(parse_files).unwrap_or_default() + let Some(tiff) = crate::cmyk::parse_tiff(&self.bytes) else { return vec![] }; + tiff.ifds.first().and_then(|ifd| ifd.string(craft_tiff::tags::IMAGE_DESCRIPTION)).map(parse_files).unwrap_or_default() } /// The clipping path a separated image's file draws it through, in its pixel space, as /// [`Self::separated_tiff_clipped`] noted it; `None` for other images. Reads only the TIFF's /// first directory. pub fn separated_clip(&self) -> Option { - let (_, mut d) = crate::cmyk::tiff(&self.bytes)?; - let text = d.get_tag_ascii_string(tiff::tags::Tag::ImageDescription).ok()?; + let tiff = crate::cmyk::parse_tiff(&self.bytes)?; + let text = tiff.ifds.first()?.string(craft_tiff::tags::IMAGE_DESCRIPTION)?; let json = unhex(text.lines().find_map(|l| l.strip_prefix(CLIP_MARK))?, MAX_CLIP)?; serde_json::from_str(&json).ok() } @@ -333,13 +365,13 @@ impl ImageBlob { if !self.is_separated() { return vec![]; } - let Some((_, mut d)) = crate::cmyk::tiff(&self.bytes) else { return vec![] }; + let Some(tiff) = crate::cmyk::parse_tiff(&self.bytes) else { return vec![] }; let mut inks = vec![]; - while d.more_images() && inks.len() < MAX_PLATES { - if d.next_image().is_err() { + for ifd in tiff.ifds.iter().skip(1) { + if inks.len() >= MAX_PLATES { break; } - let plate = d.get_tag_ascii_string(tiff::tags::Tag::ImageDescription).ok().as_deref().and_then(parse_description); + let plate = ifd.string(craft_tiff::tags::IMAGE_DESCRIPTION).and_then(parse_description); inks.extend(plate.filter(|(name, _)| !PROCESS_PLATES.contains(&name.as_str()))); } inks @@ -369,27 +401,41 @@ impl ImageBlob { /// The plates of TIFF `bytes`, each the size of its first image. fn read_plates(bytes: &[u8]) -> Option { - let (_, mut d) = crate::cmyk::tiff(bytes)?; - let (w, h) = d.dimensions().ok()?; - let n = usize::try_from(u64::from(w) * u64::from(h)).ok()?; + let tiff = crate::cmyk::parse_tiff(bytes)?; + if tiff.ifds.len() > MAX_DIRECTORIES { + return None; + } + let first = tiff.ifds.first()?.image().ok()?; + let (w, h) = (first.width, first.height); let mut plates = vec![]; - // Every plate is read: a file with more than [`MAX_PLATES`] is refused ([`Separated::fits`]), - // not cut short, and so is one with more than [`MAX_DIRECTORIES`] directories. - let mut directories = 1usize; - while d.more_images() { - directories += 1; - if directories > MAX_DIRECTORIES { + for (page, ifd) in tiff.ifds.iter().enumerate().skip(1) { + if plates.len() >= MAX_PLATES { return None; } - d.next_image().ok()?; - let Some((name, cmyk)) = d.get_tag_ascii_string(tiff::tags::Tag::ImageDescription).ok().as_deref().and_then(parse_description) else { + let Some((name, cmyk)) = ifd.string(craft_tiff::tags::IMAGE_DESCRIPTION).and_then(parse_description) else { continue; }; - // Checked before the plate is decoded. - if d.dimensions().ok()? != (w, h) || !matches!(d.colortype().ok()?, tiff::ColorType::Gray(8)) || !Separated::fits(w, h, plates.len() + 1) { + let info = ifd.image().ok()?; + if (info.width, info.height) != (w, h) + || !matches!(info.photometric, 0 | 1) + || info.samples_per_pixel != 1 + || info.bits_per_sample.first().copied() != Some(8) + || !Separated::fits(w, h, plates.len() + 1) + { return None; } - let data = crate::cmyk::read_samples(&mut d, n, 1)?.into_iter().map(|v| 255 - v).collect(); + let mut opts = craft_image_codecs::DecodeOptions::default(); + opts.keep_orientation = true; + opts.limits.max_pixels = crate::MAX_RASTER_ALLOC / 4; + opts.limits.max_alloc = crate::MAX_RASTER_ALLOC; + let decoded = craft_image_codecs::decode_tiff_page(bytes, page, &opts).ok()?; + if decoded.dimensions() != (w, h) + || decoded.layout() != craft_image_codecs::ChannelLayout::Gray + || decoded.sample_type() != craft_image_codecs::SampleType::U8 + { + return None; + } + let data = decoded.into_data().into_iter().map(|v| 255 - v).collect(); plates.push(InkPlate { name, cmyk, data }); } Separated::new(w, h, plates) @@ -465,19 +511,46 @@ mod tests { assert_eq!(ImageBlob::separated_tiff(&s, None, &files).unwrap().separated_clip(), None); } + fn test_ifd_cmyk() -> craft_tiff::IfdBuilder { + use craft_tiff::{IfdBuilder, ImageData, Value, tags}; + let mut ifd = IfdBuilder::new(); + ifd.set(tags::IMAGE_WIDTH, Value::Long(vec![1])) + .set(tags::IMAGE_LENGTH, Value::Long(vec![1])) + .set(tags::BITS_PER_SAMPLE, Value::Short(vec![8; 4])) + .set(tags::COMPRESSION, Value::Short(vec![1])) + .set(tags::PHOTOMETRIC, Value::Short(vec![5])) + .set(tags::SAMPLES_PER_PIXEL, Value::Short(vec![4])) + .set(tags::PLANAR_CONFIGURATION, Value::Short(vec![1])) + .set_image(ImageData::Strips { rows_per_strip: 1, strips: vec![vec![0, 0, 0, 0]] }); + ifd + } + + fn test_ifd_gray(desc: Option) -> craft_tiff::IfdBuilder { + use craft_tiff::{IfdBuilder, ImageData, Value, tags}; + let mut ifd = IfdBuilder::new(); + ifd.set(tags::IMAGE_WIDTH, Value::Long(vec![1])) + .set(tags::IMAGE_LENGTH, Value::Long(vec![1])) + .set(tags::BITS_PER_SAMPLE, Value::Short(vec![8])) + .set(tags::COMPRESSION, Value::Short(vec![1])) + .set(tags::PHOTOMETRIC, Value::Short(vec![1])) + .set(tags::SAMPLES_PER_PIXEL, Value::Short(vec![1])) + .set(tags::PLANAR_CONFIGURATION, Value::Short(vec![1])) + .set_image(ImageData::Strips { rows_per_strip: 1, strips: vec![vec![255]] }); + if let Some(d) = desc { + ifd.set(tags::IMAGE_DESCRIPTION, Value::Ascii(d)); + } + ifd + } + #[test] fn a_tiff_with_more_plates_than_are_read_is_refused() { - use tiff::encoder::{TiffEncoder, colortype}; let tiff = |plates: usize| { - let mut out = Cursor::new(Vec::new()); - let mut enc = TiffEncoder::new(&mut out).unwrap(); - enc.write_image::(1, 1, &[0, 0, 0, 0]).unwrap(); + let mut ifds = vec![test_ifd_cmyk()]; for i in 0..plates { - let mut img = enc.new_image::(1, 1).unwrap(); - img.encoder().write_tag(tiff::tags::Tag::ImageDescription, description(&plate(&format!("S{i}"), [0.0; 4], &[0])).as_str()).unwrap(); - img.write_data(&[255]).unwrap(); + ifds.push(test_ifd_gray(Some(description(&plate(&format!("S{i}"), [0.0; 4], &[0]))))); } - ImageBlob::new("image/tiff", out.into_inner()) + let bytes = craft_tiff::TiffWriter::new(craft_tiff::ByteOrder::Little, false).write(&ifds).unwrap(); + ImageBlob::new("image/tiff", bytes) }; assert_eq!(tiff(MAX_PLATES).separated().map(|s| s.plates.len()), Some(MAX_PLATES)); let over = tiff(MAX_PLATES + 1); @@ -488,19 +561,13 @@ mod tests { #[test] fn a_tiff_with_more_directories_than_a_composite_and_its_plates_is_refused() { - use tiff::encoder::{TiffEncoder, colortype}; let tiff = |others: usize| { - let mut out = Cursor::new(Vec::new()); - let mut enc = TiffEncoder::new(&mut out).unwrap(); - enc.write_image::(1, 1, &[0, 0, 0, 0]).unwrap(); - let mut img = enc.new_image::(1, 1).unwrap(); - img.encoder().write_tag(tiff::tags::Tag::ImageDescription, description(&plate("S", [0.0; 4], &[0])).as_str()).unwrap(); - img.write_data(&[255]).unwrap(); - // Directories that are not plates. + let mut ifds = vec![test_ifd_cmyk(), test_ifd_gray(Some(description(&plate("S", [0.0; 4], &[0]))))]; for _ in 0..others { - enc.write_image::(1, 1, &[255]).unwrap(); + ifds.push(test_ifd_gray(None)); } - ImageBlob::new("image/tiff", out.into_inner()) + let bytes = craft_tiff::TiffWriter::new(craft_tiff::ByteOrder::Little, false).write(&ifds).unwrap(); + ImageBlob::new("image/tiff", bytes) }; let most = tiff(MAX_PLATES - 1); assert!(most.is_separated() && most.separated().is_some()); diff --git a/crates/effects/Cargo.toml b/crates/effects/Cargo.toml index 6d58ad9d74..e737bc5ad8 100644 --- a/crates/effects/Cargo.toml +++ b/crates/effects/Cargo.toml @@ -17,10 +17,10 @@ vectorcraft-text = { workspace = true } vectorcraft-plugins = { workspace = true } vectorcraft-trace = { workspace = true } image = { workspace = true } +craft-image-codecs = { workspace = true } kurbo = { workspace = true } -# Effect › SVG Filters draws its filters with resvg (MIT OR Apache-2.0), at the usvg version the -# workspace reads SVG with; raster-images decodes the object's pixels it hands the filter as a PNG. -resvg = { version = "0.48", default-features = false, features = ["raster-images"] } +# Effect › SVG Filters draws its filters with craft-svg's resvg (`tree-render`). +craft-svg = { workspace = true, features = ["tree-render"] } # The number lists of filter attributes, read as usvg reads them (MIT OR Apache-2.0; already used by usvg). svgtypes = "0.16" serde_json = { workspace = true } diff --git a/crates/effects/src/pixel/loaded.rs b/crates/effects/src/pixel/loaded.rs index bb885b239c..6226b3b56b 100644 --- a/crates/effects/src/pixel/loaded.rs +++ b/crates/effects/src/pixel/loaded.rs @@ -85,9 +85,15 @@ impl LoadedTexture { /// Its [`TEXTURE_IMAGE`] value: the gray levels as a grayscale PNG, base64; `None` when the /// PNG can't be written. pub fn to_stored(&self) -> Option { - let img = image::GrayImage::from_raw(self.width, self.height, self.gray.clone())?; - let mut png = Vec::new(); - img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?; + let img = craft_image_codecs::Image::from_raw( + self.width, + self.height, + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U8, + self.gray.clone(), + ) + .ok()?; + let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; Some(base64_encode(&png)) } @@ -95,21 +101,30 @@ impl LoadedTexture { /// `None` when `png` isn't a PNG or holds no pixels. /// `None` too when its gray levels would take the live textures past [`MAX_LIVE`]. fn from_png(png: &[u8]) -> Option { - let reader = || { - let mut reader = image::ImageReader::with_format(Cursor::new(png), image::ImageFormat::Png); - let mut limits = image::Limits::default(); - limits.max_alloc = Some(vectorcraft_doc::MAX_RASTER_ALLOC); - reader.limits(limits); - reader - }; - let (w, h) = reader().into_dimensions().ok()?; + let (w, h) = png_ihdr_size(png)?; let gray = (w as usize).checked_mul(h as usize)?; if LIVE.load(Ordering::Relaxed).saturating_add(gray) > MAX_LIVE { return None; } - let img = reader().decode().ok()?.to_luma8(); + let mut opts = craft_image_codecs::DecodeOptions::default(); + opts.limits.max_alloc = vectorcraft_doc::MAX_RASTER_ALLOC as u64; + let img = craft_image_codecs::decode_as_with(craft_image_codecs::Format::Png, png, &opts).ok()?; let (width, height) = img.dimensions(); - (width > 0 && height > 0).then(|| Self::new(width, height, img.into_raw())) + if width == 0 || height == 0 { + return None; + } + let luma = image::RgbaImage::from_raw(width, height, img.to_rgba8()).map(image::DynamicImage::ImageRgba8)?.into_luma8().into_raw(); + Some(Self::new(width, height, luma)) + } + + /// Read `(width, height)` from a PNG's IHDR chunk without decoding pixels. + fn png_ihdr_size(png: &[u8]) -> Option<(u32, u32)> { + if png.len() < 24 || &png[..8] != b"\x89PNG\r\n\x1a\n" || &png[12..16] != b"IHDR" { + return None; + } + let w = u32::from_be_bytes(png[16..20].try_into().ok()?); + let h = u32::from_be_bytes(png[20..24].try_into().ok()?); + Some((w, h)) } /// The surface's height (points) at `p` (points at 100 %, from the object's center): the gray diff --git a/crates/effects/src/svg_filter.rs b/crates/effects/src/svg_filter.rs index 3877a60ae9..96ce5a8d03 100644 --- a/crates/effects/src/svg_filter.rs +++ b/crates/effects/src/svg_filter.rs @@ -7,7 +7,8 @@ use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use resvg::{tiny_skia, usvg}; +use craft_svg::tree::draw::{resvg, tiny_skia}; +use craft_svg::tree::usvg; use serde_json::Value; use usvg::roxmltree; use vectorcraft_doc::SvgFilter; @@ -622,17 +623,31 @@ fn write_drop_shadow(n: roxmltree::Node, input: &str, result: Option<&str>, name /// first bytes whatever its `data:` URL says, of at most [`MAX_IMAGE_PIXELS`] pixels by its header. /// `None` for anything else, SVG and compressed SVG included. fn raster_image_sized(data: Arc>) -> Option<(usvg::ImageKind, u64)> { - let format = image::guess_format(&data).ok()?; - let (w, h) = image::ImageReader::with_format(std::io::Cursor::new(data.as_slice()), format).into_dimensions().ok()?; + let format = craft_image_codecs::detect(&data)?; + let (w, h) = match format { + craft_image_codecs::Format::Png => { + if data.len() < 24 || &data[..8] != b"\x89PNG\r\n\x1a\n" || &data[12..16] != b"IHDR" { + return None; + } + (u32::from_be_bytes(data[16..20].try_into().ok()?), u32::from_be_bytes(data[20..24].try_into().ok()?)) + } + craft_image_codecs::Format::Jpeg => { + let mut opts = craft_image_codecs::DecodeOptions::default(); + opts.limits.max_pixels = MAX_IMAGE_PIXELS; + craft_image_codecs::decode_as_with(craft_image_codecs::Format::Jpeg, &data, &opts).ok()?.dimensions() + } + craft_image_codecs::Format::Gif | craft_image_codecs::Format::WebP => craft_image_codecs::probe_size(&data).ok()?, + _ => return None, + }; let pixels = u64::from(w) * u64::from(h); if pixels == 0 || pixels > MAX_IMAGE_PIXELS { return None; } let kind = match format { - image::ImageFormat::Png => usvg::ImageKind::PNG(data), - image::ImageFormat::Jpeg => usvg::ImageKind::JPEG(data), - image::ImageFormat::Gif => usvg::ImageKind::GIF(data), - image::ImageFormat::WebP => usvg::ImageKind::WEBP(data), + craft_image_codecs::Format::Png => usvg::ImageKind::PNG(data), + craft_image_codecs::Format::Jpeg => usvg::ImageKind::JPEG(data), + craft_image_codecs::Format::Gif => usvg::ImageKind::GIF(data), + craft_image_codecs::Format::WebP => usvg::ImageKind::WEBP(data), _ => return None, }; Some((kind, pixels)) @@ -1461,14 +1476,17 @@ fn png_of(data: &[u8], w: usize, x0: usize, y0: usize, x1: usize, y1: usize) -> straight.extend_from_slice(&[un(p[0]), un(p[1]), un(p[2]), p[3]]); } } - let mut png = vec![]; - let encoder = image::codecs::png::PngEncoder::new_with_quality( - &mut png, - image::codecs::png::CompressionType::Fast, - image::codecs::png::FilterType::NoFilter, - ); - encoder.write_image(&straight, (x1 - x0) as u32, (y1 - y0) as u32, image::ExtendedColorType::Rgba8).ok()?; - Some(png) + let raw = craft_image_codecs::Image::from_raw( + (x1 - x0) as u32, + (y1 - y0) as u32, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + straight, + ) + .ok()?; + let mut opts = craft_image_codecs::EncodeOptions::default(); + opts.png_compression = craft_image_codecs::PngCompression::Fast; + craft_image_codecs::encode_with(&raw, craft_image_codecs::Format::Png, &opts).ok() } /// `a` as an SVG `matrix(…)`. diff --git a/crates/effects/src/svg_filter/tests.rs b/crates/effects/src/svg_filter/tests.rs index df1956f3f0..62335c60da 100644 --- a/crates/effects/src/svg_filter/tests.rs +++ b/crates/effects/src/svg_filter/tests.rs @@ -364,16 +364,15 @@ fn the_filter_is_drawn_and_written_from_its_filter_parts_alone() { #[test] fn filter_images_are_small_raster_images() { fn png(w: u32, h: u32) -> Vec { - let mut out = vec![]; - image::ImageEncoder::write_image( - image::codecs::png::PngEncoder::new(&mut out), - &vec![0; (w * h * 4) as usize], + let img = craft_image_codecs::Image::from_raw( w, h, - image::ExtendedColorType::Rgba8, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + vec![0; (w * h * 4) as usize], ) .unwrap(); - out + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap() } let raster_image = |data| raster_image_sized(data).map(|(kind, _)| kind); assert!(matches!(raster_image(Arc::new(png(2, 2))), Some(usvg::ImageKind::PNG(_)))); @@ -391,8 +390,11 @@ fn filter_images_are_small_raster_images() { /// A 2 × 2 PNG whose header claims `w` × `h` pixels (its IHDR rewritten, with the CRC fixed). fn png_claiming(w: u32, h: u32) -> Vec { - let mut out = vec![]; - image::ImageEncoder::write_image(image::codecs::png::PngEncoder::new(&mut out), &[0; 16], 2, 2, image::ExtendedColorType::Rgba8).unwrap(); + let mut out = craft_image_codecs::encode( + &craft_image_codecs::Image::from_raw(2, 2, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, vec![0; 16]).unwrap(), + craft_image_codecs::Format::Png, + ) + .unwrap(); out[16..20].copy_from_slice(&w.to_be_bytes()); out[20..24].copy_from_slice(&h.to_be_bytes()); let crc = crc32(&out[12..29]); diff --git a/crates/effects/src/tests/imageoutline.rs b/crates/effects/src/tests/imageoutline.rs index 5ef3955254..9c2a5543ee 100644 --- a/crates/effects/src/tests/imageoutline.rs +++ b/crates/effects/src/tests/imageoutline.rs @@ -15,10 +15,13 @@ fn fx(id: &str) -> Effect { } /// `img` encoded as `format`. -fn encoded(img: image::DynamicImage, format: image::ImageFormat) -> Vec { - let mut out = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut out), format).unwrap(); - out +fn encoded(img: image::DynamicImage, format: craft_image_codecs::Format) -> Vec { + let (layout, data) = match format { + craft_image_codecs::Format::Jpeg => (craft_image_codecs::ChannelLayout::Rgb, img.to_rgb8().into_raw()), + _ => (craft_image_codecs::ChannelLayout::Rgba, img.to_rgba8().into_raw()), + }; + let raw = craft_image_codecs::Image::from_raw(img.width(), img.height(), layout, craft_image_codecs::SampleType::U8, data).unwrap(); + craft_image_codecs::encode(&raw, format, &craft_image_codecs::EncodeOptions::default()).unwrap() } /// A 100×100 RGBA image, transparent but for an opaque disc of radius 30 in its middle. @@ -130,7 +133,7 @@ fn outline_object_follows_the_opaque_area_of_an_image_with_alpha() { let gray_alpha = image::DynamicImage::ImageLumaA8(disc().to_luma_alpha8()); let deep = image::DynamicImage::ImageRgba16(disc().to_rgba16()); for (name, img) in [("rgba", disc()), ("gray and alpha", gray_alpha), ("16 bits a channel", deep)] { - let (d, n) = image_doc(encoded(img, image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1); + let (d, n) = image_doc(encoded(img, craft_image_codecs::Format::Png), vec![stroke(vec![fx("path.outlineObject")])], 1); let rows = row_bounds(&d, &n); assert_eq!(rows.len(), 1, "{name}"); // The disc runs from 70 to 130; the frame from 50 to 150. @@ -143,9 +146,9 @@ fn outline_object_follows_the_frame_of_an_image_without_transparency() { let opaque = image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(100, 100, image::Rgb([0, 0, 255]))); let solid = image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(100, 100, image::Rgba([0, 0, 255, 200]))); let formats = [ - ("jpeg", encoded(opaque.clone(), image::ImageFormat::Jpeg)), - ("rgb png", encoded(opaque, image::ImageFormat::Png)), - ("rgba png, every pixel more than half opaque", encoded(solid, image::ImageFormat::Png)), + ("jpeg", encoded(opaque.clone(), craft_image_codecs::Format::Jpeg)), + ("rgb png", encoded(opaque, craft_image_codecs::Format::Png)), + ("rgba png, every pixel more than half opaque", encoded(solid, craft_image_codecs::Format::Png)), ]; for (name, bytes) in formats { let (d, n) = image_doc(bytes, vec![stroke(vec![fx("path.outlineObject")])], 1); @@ -165,7 +168,7 @@ fn convert_to_shape_keeps_the_frame_beside_outline_object() { let mut fill = FillLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0))); fill.effects = vec![rect.clone()]; let items = vec![AppearanceItem::Fill(fill), stroke(vec![fx("path.outlineObject")]), stroke(vec![rect, fx("path.outlineObject")])]; - let (d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), items, 2); + let (d, n) = image_doc(encoded(disc(), craft_image_codecs::Format::Png), items, 2); let rows = row_bounds(&d, &n); assert_eq!(rows.len(), 3, "{rows:?}"); assert!(near(rows[0], [50.0, 50.0, 150.0, 150.0], 1e-9), "{rows:?}"); @@ -179,7 +182,7 @@ fn convert_to_shape_keeps_the_frame_beside_outline_object() { #[test] fn a_transparent_image_gives_outline_object_nothing_to_paint() { let clear = image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(100, 100, image::Rgba([0, 0, 0, 100]))); - let (d, n) = image_doc(encoded(clear, image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1); + let (d, n) = image_doc(encoded(clear, craft_image_codecs::Format::Png), vec![stroke(vec![fx("path.outlineObject")])], 1); assert!(row_bounds(&d, &n).is_empty()); let art = reshape::reshape(Some(&d), &n, None).unwrap(); assert!(matches!(art.children().unwrap().as_slice(), [only] if matches!(only.kind, NodeKind::Image(_)))); @@ -190,7 +193,7 @@ fn the_outline_follows_the_images_own_pixels_and_placement() { // Pixels kept on the image itself (art made outside a document), placed at half size. let (_, mut n) = image_doc(vec![], vec![stroke(vec![fx("path.outlineObject")])], 1); if let NodeKind::Image(im) = &mut n.kind { - im.pixels = Some(Arc::new(ImageBlob::new("image/png", encoded(disc(), image::ImageFormat::Png)))); + im.pixels = Some(Arc::new(ImageBlob::new("image/png", encoded(disc(), craft_image_codecs::Format::Png)))); im.xf = Affine::translate((10.0, 20.0)) * Affine::scale(0.5); } let art = reshape::reshape(None, &n, None).unwrap(); @@ -206,7 +209,7 @@ fn an_off_center_outline_turns_and_reflects_with_a_smaller_copy_of_the_pixels() let half = image::DynamicImage::ImageRgba8(image::RgbaImage::from_fn(60, 30, |x, y| { image::Rgba([255, 0, 0, if (6..20).contains(&x) && (3..12).contains(&y) { 255 } else { 0 }]) })); - let (d, mut n) = image_doc(encoded(half, image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1); + let (d, mut n) = image_doc(encoded(half, craft_image_codecs::Format::Png), vec![stroke(vec![fx("path.outlineObject")])], 1); let xf = Affine::translate((100.0, 40.0)) * Affine::rotate(std::f64::consts::FRAC_PI_2) * Affine::scale_non_uniform(-1.0, 1.0); if let NodeKind::Image(im) = &mut n.kind { (im.width, im.height, im.xf) = (120, 60, xf); @@ -221,7 +224,7 @@ fn an_off_center_outline_turns_and_reflects_with_a_smaller_copy_of_the_pixels() #[test] fn an_image_in_a_group_exports_with_its_outline() { - let (mut d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1); + let (mut d, n) = image_doc(encoded(disc(), craft_image_codecs::Format::Png), vec![stroke(vec![fx("path.outlineObject")])], 1); let l = d.layers[0].id; d.remove(n.id).unwrap(); let g = d.alloc_id(); @@ -256,7 +259,7 @@ fn baked_strokes(d: &Document) -> Vec { fn an_image_under_a_clipping_mask_or_with_an_opacity_mask_exports_with_its_outline() { let disc_outline = |paths: &[Rect]| matches!(paths, [b] if near(*b, [70.0, 70.0, 130.0, 130.0], 0.5)); // Under a clipping mask that covers the whole image. - let (mut d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1); + let (mut d, n) = image_doc(encoded(disc(), craft_image_codecs::Format::Png), vec![stroke(vec![fx("path.outlineObject")])], 1); let l = d.layers[0].id; d.remove(n.id).unwrap(); let clip = Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), Default::default()); @@ -265,7 +268,7 @@ fn an_image_under_a_clipping_mask_or_with_an_opacity_mask_exports_with_its_outli let paths = baked_strokes(&d); assert!(disc_outline(&paths), "{paths:?}"); // With an opacity mask. - let (mut d, mut n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1); + let (mut d, mut n) = image_doc(encoded(disc(), craft_image_codecs::Format::Png), vec![stroke(vec![fx("path.outlineObject")])], 1); let mut white = Node::path(NodeId(999), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), Default::default()); white.appearance.set_fill(Paint::solid(Color::WHITE)); n.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(Node::group(NodeId(998), vec![Arc::new(white)]), true))); @@ -279,7 +282,7 @@ fn an_image_under_a_clipping_mask_or_with_an_opacity_mask_exports_with_its_outli fn outline_object_on_a_fill_and_on_an_indexed_image_follows_the_opaque_area() { let mut fill = FillLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0))); fill.effects = vec![fx("path.outlineObject")]; - let (d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![AppearanceItem::Fill(fill)], 1); + let (d, n) = image_doc(encoded(disc(), craft_image_codecs::Format::Png), vec![AppearanceItem::Fill(fill)], 1); let rows = row_bounds(&d, &n); assert!(matches!(rows.as_slice(), [b] if near(*b, [70.0, 70.0, 130.0, 130.0], 0.5)), "{rows:?}"); // A palette image whose first color is transparent (a tRNS chunk). @@ -308,15 +311,18 @@ fn an_image_too_large_or_too_complex_to_outline_keeps_its_frame() { } // A checkerboard of 2 px squares, whose outline would need more than 100,000 anchor points. let checker = image::RgbaImage::from_fn(640, 640, |x, y| image::Rgba([0, 0, 0, if (x / 2 + y / 2) % 2 == 0 { 255 } else { 0 }])); - let (d, n) = - image_doc(encoded(image::DynamicImage::ImageRgba8(checker), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1); + let (d, n) = image_doc( + encoded(image::DynamicImage::ImageRgba8(checker), craft_image_codecs::Format::Png), + vec![stroke(vec![fx("path.outlineObject")])], + 1, + ); assert!(matches!(row_bounds(&d, &n).as_slice(), [b] if near(*b, [50.0, 50.0, 150.0, 150.0], 1e-9))); } #[test] fn an_outline_is_traced_once_for_its_pixels_and_dropped_with_them() { let traces = || reshape::TRACES.with(std::cell::Cell::get); - let (d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1); + let (d, n) = image_doc(encoded(disc(), craft_image_codecs::Format::Png), vec![stroke(vec![fx("path.outlineObject")])], 1); let NodeKind::Image(im) = &n.kind else { panic!("not an image") }; let before = traces(); let first = reshape::opaque_area(&[Some(&d)], im).unwrap(); @@ -331,7 +337,7 @@ fn an_outline_is_traced_once_for_its_pixels_and_dropped_with_them() { // Once the document and its pixels are gone, the next trace drops their entry. drop(d); assert!(pixels.upgrade().is_none()); - let (other, _) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![], 1); + let (other, _) = image_doc(encoded(disc(), craft_image_codecs::Format::Png), vec![], 1); reshape::opaque_area(&[Some(&other)], im).unwrap(); assert_eq!(traces(), before + 2); assert!(!reshape::keeps_outline(&pixels)); diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index b46678804b..0aee7edd7c 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -16,7 +16,7 @@ bundled-fonts = ["vectorcraft-text/bundled-fonts"] # HEIC and HEIF images open and place, decoded by heic-rs (an HEVC decoder). A build without this # feature still recognizes the files and refuses them with a message. The apps list it beside # `bundled-fonts`. -heif = ["dep:heic-rs", "dep:rayon"] +heif = ["dep:craft-heif"] [dependencies] # Which paths stored in documents may be opened. @@ -44,12 +44,9 @@ vectorcraft-js = { workspace = true } # The commands' parameter schemas (schemas.rs). vectorcraft-apischema = { workspace = true } image = { workspace = true } -jxl-oxide = { workspace = true } -jxl-color = { workspace = true } -jxl-grid = { workspace = true } -hayro-jpeg2000 = { version = "=0.3.5", default-features = false, features = ["std", "simd"] } -# Pure Rust, no unsafe; pinned at the version photocraft-heif uses. -heic-rs = { version = "=0.1.4", default-features = false, features = ["std"], optional = true } +craft-image-codecs = { workspace = true } +craft-jxl = { workspace = true } +craft-heif = { workspace = true, optional = true } flate2 = { workspace = true } chrono = { workspace = true } # The XML parts of Word documents placed as type (place/docx.rs). @@ -72,11 +69,6 @@ rustix = { workspace = true, features = ["std", "process"] } [target.'cfg(windows)'.dependencies] same-file = "1.0.6" -# The tiles of a HEIC photo decode in parallel on native; wasm stays single-threaded. -[target.'cfg(not(target_arch = "wasm32"))'.dependencies] -heic-rs = { version = "=0.1.4", default-features = false, features = ["std", "parallel"], optional = true } -rayon = { version = "1.12", optional = true } - [dev-dependencies] vectorcraft-affinity = { workspace = true, features = ["synth"] } crc32fast = { workspace = true } @@ -89,9 +81,6 @@ vectorcraft-pdf = { workspace = true, features = ["read-count"] } wat = { workspace = true } # Zstandard streams for the Illustrator editing data fuzz tests. ruzstd = { workspace = true } -# JPEG XL files for the `.jxl` open and place tests. -zune-jpegxl = { workspace = true } -zune-core = { workspace = true } # The JavaScript parser's lexer, compared with the script checker's on the same scripts. vectorcraft-js = { workspace = true } # A bundled font's own glyph boxes, for the glyph bounds tests. diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index 6eb21c9a63..7be70c88dc 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -147,9 +147,8 @@ fn is_of_kind(d: &Document, n: &Node, kind: &str) -> bool { /// Are the encoded image `bytes` grayscale or 1-bit? Reads only the header. fn is_gray(bytes: &[u8]) -> bool { - use image::ImageDecoder as _; - let decoder = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok().and_then(|r| r.into_decoder().ok()); - decoder.is_some_and(|d| matches!(d.color_type(), image::ColorType::L8 | image::ColorType::La8 | image::ColorType::L16 | image::ColorType::La16)) + craft_image_codecs::decode(bytes) + .is_ok_and(|img| matches!(img.layout(), craft_image_codecs::ChannelLayout::Gray | craft_image_codecs::ChannelLayout::GrayA)) } fn filter(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/addons/color/tests.rs b/crates/engine/src/cmd/addons/color/tests.rs index ed8137d6a9..4af9769386 100644 --- a/crates/engine/src/cmd/addons/color/tests.rs +++ b/crates/engine/src/cmd/addons/color/tests.rs @@ -111,7 +111,41 @@ fn image(s: &mut Session, key: &str, blob: vectorcraft_doc::ImageBlob, x: f64) - fn png(img: image::DynamicImage) -> vectorcraft_doc::ImageBlob { let mut bytes = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| bytes.extend_from_slice(&__b)) + } + .unwrap(); vectorcraft_doc::ImageBlob::png(bytes) } diff --git a/crates/engine/src/cmd/addons/document/tests.rs b/crates/engine/src/cmd/addons/document/tests.rs index 43e86caf52..d1bd77727d 100644 --- a/crates/engine/src/cmd/addons/document/tests.rs +++ b/crates/engine/src/cmd/addons/document/tests.rs @@ -228,7 +228,41 @@ fn export_all_open_documents_writes_one_file_each() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 100, "height": 100, "name": "pic"})).unwrap(); let mut png = vec![]; - image::RgbaImage::from_pixel(4, 4, image::Rgba([1, 2, 3, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(4, 4, image::Rgba([1, 2, 3, 255]))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); s.execute("file.place", &json!({"name": "a.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); s.execute("document.save", &json!({"path": dir.join("pic.svg"), "format": "svg", "options": {"images": "link"}})).unwrap(); let saved: Vec<_> = std::fs::read_dir(&dir).unwrap().filter_map(|e| e.ok()).filter(|e| e.path().is_file()).collect(); diff --git a/crates/engine/src/cmd/addons/image.rs b/crates/engine/src/cmd/addons/image.rs index 898c28c707..15eaf7b473 100644 --- a/crates/engine/src/cmd/addons/image.rs +++ b/crates/engine/src/cmd/addons/image.rs @@ -412,23 +412,36 @@ pub(crate) fn clear(blob: &ImageBlob, settings: &Settings, mut kept: Option<&mut bad(cmd, "every pixel matches the background: no image would be left") }); } - let out = match (px, gray) { - (Pixels::Eight(img), false) => DynamicImage::ImageRgba8(img), - (Pixels::Sixteen(img), false) => DynamicImage::ImageRgba16(img), - (Pixels::Eight(img), true) => { - DynamicImage::ImageLumaA8(ImageBuffer::from_fn(w, h, |x, y| LumaA([img.get_pixel(x, y).0[0], img.get_pixel(x, y).0[3]]))) + let raw = match (px, gray) { + (Pixels::Eight(img), false) => { + craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, img.into_raw()) } - (Pixels::Sixteen(img), true) => { - DynamicImage::ImageLumaA16(ImageBuffer::from_fn(w, h, |x, y| LumaA([img.get_pixel(x, y).0[0], img.get_pixel(x, y).0[3]]))) - } - }; - let mut png = Vec::new(); - let mut encoder = image::codecs::png::PngEncoder::new(&mut png); - if let Some(icc) = icc { - use image::ImageEncoder as _; - encoder.set_icc_profile(icc).map_err(|e| bad(cmd, e.to_string()))?; + (Pixels::Sixteen(img), false) => craft_image_codecs::Image::from_raw( + w, + h, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + img.into_raw().into_iter().flat_map(u16::to_ne_bytes).collect(), + ), + (Pixels::Eight(img), true) => craft_image_codecs::Image::from_raw( + w, + h, + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U8, + img.pixels().flat_map(|p| [p.0[0], p.0[3]]).collect(), + ), + (Pixels::Sixteen(img), true) => craft_image_codecs::Image::from_raw( + w, + h, + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + img.pixels().flat_map(|p| [p.0[0], p.0[3]]).flat_map(u16::to_ne_bytes).collect(), + ), } - out.write_with_encoder(encoder).map_err(|e| bad(cmd, e.to_string()))?; + .map_err(|e| bad(cmd, e.to_string()))? + .with_icc(icc); + let mut png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map_err(|e| bad(cmd, e.to_string()))?; // The resolution the file declares, which sizes the image at 100% when it is replaced or relinked. if let Some(r) = ppi::resolution(&blob.bytes) { png = ppi::with_png_resolution(&png, r); @@ -440,33 +453,34 @@ pub(crate) fn clear(blob: &ImageBlob, settings: &Settings, mut kept: Option<&mut /// can't be decoded or is too large to change is an error. The pixels are kept in `kept`, when it /// is given, if a copy of them fits the decode allowance beside the work. Errors are command `cmd`'s. fn decode(blob: &ImageBlob, kept: Option<&mut DecodedImages>, cmd: &str) -> Result<(Arc, bool, Option>)> { - let reader = || { - image::ImageReader::new(Cursor::new(blob.bytes.as_slice())).with_guessed_format().map_err(|_| bad(cmd, "the image's pixels can't be read")) - }; - let mut decoder = reader()?.into_decoder().map_err(|e| bad(cmd, format!("the image's pixels can't be read: {e}")))?; - // The ICC profile the colors are in goes with them into the PNG. - let (w, h, kind, icc) = { - use image::ImageDecoder as _; - let (w, h) = decoder.dimensions(); - (w, h, decoder.color_type(), decoder.icc_profile().ok().flatten()) - }; - drop(decoder); - // The file's pixels, those worked on (as many again for the PNG made of them) and the work, - // checked from the header before anything is decoded. - let deep = kind.bytes_per_pixel() > kind.channel_count(); - let per_pixel = u64::from(kind.bytes_per_pixel()) + 2 * if deep { 8 } else { 4 } + WORK_BYTES; + let mut opts = craft_image_codecs::DecodeOptions::default(); + opts.limits.max_alloc = MAX_RASTER_ALLOC; + let img = craft_image_codecs::decode_with(&blob.bytes, &opts).map_err(|e| match e { + craft_image_codecs::CodecError::LimitExceeded(_) => bad(cmd, "the image is too large to change"), + _ => bad(cmd, format!("the image's pixels can't be read: {e}")), + })?; + let (w, h) = img.dimensions(); + let icc = img.icc.clone(); + let deep = img.sample_type() == craft_image_codecs::SampleType::U16; + let gray = matches!(img.layout(), craft_image_codecs::ChannelLayout::Gray | craft_image_codecs::ChannelLayout::GrayA); + let per_pixel = u64::from(img.layout().channels() as u32 * img.sample_type().bytes() as u32) + 2 * if deep { 8 } else { 4 } + WORK_BYTES; if u64::from(w).checked_mul(u64::from(h)).and_then(|n| n.checked_mul(per_pixel)).is_none_or(|n| n > MAX_RASTER_ALLOC) { return Err(bad(cmd, format!("an image of {w} × {h} pixels is too large to change"))); } - let mut reader = reader()?; - let mut limits = image::Limits::default(); - limits.max_alloc = Some(MAX_RASTER_ALLOC); - reader.limits(limits); - let img = reader.decode().map_err(|e| bad(cmd, format!("the image's pixels can't be read: {e}")))?; #[cfg(test)] DECODES.with(|c| c.set(c.get() + 1)); - let gray = matches!(img.color(), image::ColorType::L8 | image::ColorType::La8 | image::ColorType::L16 | image::ColorType::La16); - let px = Arc::new(if deep { Pixels::Sixteen(img.into_rgba16()) } else { Pixels::Eight(img.into_rgba8()) }); + let px = Arc::new(if deep { + let rgba16 = match (img.layout(), img.to_u16_samples()) { + (craft_image_codecs::ChannelLayout::Rgba, Some(v)) => v, + (craft_image_codecs::ChannelLayout::Rgb, Some(v)) => v.chunks_exact(3).flat_map(|c| [c[0], c[1], c[2], u16::MAX]).collect(), + (craft_image_codecs::ChannelLayout::GrayA, Some(v)) => v.chunks_exact(2).flat_map(|c| [c[0], c[0], c[0], c[1]]).collect(), + (craft_image_codecs::ChannelLayout::Gray, Some(v)) => v.into_iter().flat_map(|g| [g, g, g, u16::MAX]).collect(), + _ => img.to_rgba8().into_iter().map(|b| u16::from(b) * 257).collect(), + }; + Pixels::Sixteen(ImageBuffer::from_raw(w, h, rgba16).ok_or_else(|| bad(cmd, "invalid 16-bit pixel buffer"))?) + } else { + Pixels::Eight(ImageBuffer::from_raw(w, h, img.to_rgba8()).ok_or_else(|| bad(cmd, "invalid 8-bit pixel buffer"))?) + }); // A kept copy is worked on as a copy: one more set of the pixels worked on. let with_copy = per_pixel + if deep { 8 } else { 4 }; if let Some(kept) = kept diff --git a/crates/engine/src/cmd/addons/image/mask.rs b/crates/engine/src/cmd/addons/image/mask.rs index 0dd8fabe3c..7fdb0c5c3e 100644 --- a/crates/engine/src/cmd/addons/image/mask.rs +++ b/crates/engine/src/cmd/addons/image/mask.rs @@ -287,9 +287,7 @@ fn apply_color_mask(s: &mut Session, p: &Value) -> Result { /// The size in pixels of masked pixels `blob` (from its header), or the object's when it can't be /// read. fn mask_size(blob: Option<&ImageBlob>, width: u32, height: u32) -> (u32, u32) { - blob.and_then(|b| image::ImageReader::new(std::io::Cursor::new(b.bytes.as_slice())).with_guessed_format().ok()?.into_dimensions().ok()) - .filter(|(w, h)| *w > 0 && *h > 0) - .unwrap_or((width, height)) + blob.and_then(|b| b.pixel_size()).filter(|(w, h)| *w > 0 && *h > 0).unwrap_or((width, height)) } /// The mask of image node `n` made again for the image's own pixels, with the masked pixels when diff --git a/crates/engine/src/cmd/addons/image/mask/tests.rs b/crates/engine/src/cmd/addons/image/mask/tests.rs index b9b56a5e4a..1b69c709f0 100644 --- a/crates/engine/src/cmd/addons/image/mask/tests.rs +++ b/crates/engine/src/cmd/addons/image/mask/tests.rs @@ -15,7 +15,41 @@ const RED: [u8; 4] = [200, 0, 0, 255]; fn png(img: DynamicImage) -> Vec { let mut out = Vec::new(); - img.write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); out } @@ -138,7 +172,24 @@ fn applying_the_mask_makes_it_part_of_the_pixels() { assert_eq!(s.execute(APPLY_COLOR_MASK, &json!({})).unwrap(), json!({"changed": 1, "ids": [id.0]})); let d = doc(&s); assert_eq!((image_of(d, id).key, mask_of(d, id)), (m.key.clone(), None)); - let px = image::load_from_memory(&d.images[&m.key].bytes).unwrap().to_rgba8(); + let px = craft_image_codecs::decode(&d.images[&m.key].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(4, 4).0), (0, RED)); assert_eq!(drawn(d, id, 0, 0)[3], 0); assert_eq!(undo_len(&s), steps + 1); @@ -149,7 +200,23 @@ fn applying_the_mask_makes_it_part_of_the_pixels() { fn svg_image(svg: &str) -> DynamicImage { let at = svg.find("data:image/png;base64,").expect("an embedded PNG") + "data:image/png;base64,".len(); let end = at + svg[at..].find('"').unwrap(); - image::load_from_memory(&vectorcraft_format::base64_decode(&svg[at..end]).unwrap()).unwrap() + craft_image_codecs::decode(&vectorcraft_format::base64_decode(&svg[at..end]).unwrap()) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() } #[test] @@ -159,7 +226,28 @@ fn outputs_write_the_masked_pixels() { |s: &Session, format: &str| crate::cmd::fileio::encode_all(doc(s), format, &json!({"useArtboards": true})).unwrap().files.remove(0).1; let (png0, svg0, pdf0, eps0) = (export(&s, "png"), export(&s, "svg"), export(&s, "pdf"), export(&s, "eps")); s.execute(COLOR_MASK, &hide_white()).unwrap(); - let alpha = |bytes: &[u8]| image::load_from_memory(bytes).unwrap().to_rgba8().get_pixel(0, 0).0[3]; + let alpha = |bytes: &[u8]| { + craft_image_codecs::decode(bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() + .get_pixel(0, 0) + .0[3] + }; assert_eq!((alpha(&png0), alpha(&export(&s, "png"))), (255, 0), "PNG"); let svg_alpha = |bytes: &[u8]| svg_image(std::str::from_utf8(bytes).unwrap()).to_rgba8().get_pixel(0, 0).0[3]; assert_eq!((svg_alpha(&svg0), svg_alpha(&export(&s, "svg"))), (255, 0), "SVG"); @@ -344,7 +432,24 @@ fn cropping_off_the_pixel_grid_keeps_the_hidden_colors_in_the_pixels() { let d = doc(&s); let (im, m) = (image_of(d, id), mask_of(d, id).unwrap()); assert_eq!(m.from, im.key, "the mask is made for the cut pixels"); - let own = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8(); + let own = craft_image_codecs::decode(&d.images[&im.key].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert!(own.pixels().all(|p| p.0[3] == 255), "the cut pixels are the image's own, white included"); assert_eq!(drawn(d, id, 0, 0)[3], 0, "white is hidden"); s.execute(REMOVE_COLOR_MASK, &json!({"ids": [id.0]})).unwrap(); @@ -377,7 +482,24 @@ fn applying_a_mask_made_for_older_pixels_makes_it_again_and_keeps_the_size() { assert_eq!((im.width, im.height, mask_of(d, id)), (24, 20, None)); let after = d.node(id).unwrap().geometric_bounds().unwrap(); assert!((after.width() - before.width()).abs() < 1e-9 && (after.height() - before.height()).abs() < 1e-9, "{before:?} {after:?}"); - let px = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8(); + let px = craft_image_codecs::decode(&d.images[&im.key].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(10, 10).0), (0, RED)); } @@ -435,7 +557,24 @@ fn another_image_colorized_with_transparency_does_not_change_the_refusal() { s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); assert_eq!(s.execute(COLOR_MASK, &hide_white()).unwrap()["changed"], 1, "an image colorized with black takes the mask beside the other"); let m = mask_of(doc(&s), id).unwrap(); - let masked = image::load_from_memory(&doc(&s).images[&m.key].bytes).unwrap().to_luma_alpha8(); + let masked = craft_image_codecs::decode(&doc(&s).images[&m.key].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_luma_alpha8(); assert_eq!((masked.get_pixel(0, 0).0[1], masked.get_pixel(4, 4).0[1]), (0, 255), "white is hidden and black shows"); } @@ -580,7 +719,24 @@ fn masks_outside_the_layers_are_made_again() { let art = &d.node(holder_id).unwrap().extras().mask.as_ref().unwrap().art; assert_eq!(from(art), key, "in the opacity mask's art"); let m = Document::color_mask_of(art).unwrap(); - let px = image::load_from_memory(&d.images[&m.key].bytes).unwrap().to_rgba8(); + let px = craft_image_codecs::decode(&d.images[&m.key].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(1, 0).0), (0, RED)); } @@ -696,7 +852,24 @@ fn a_linked_file_read_again_on_open_takes_the_mask_again() { let d = doc(&s); let (im, m) = (image_of(d, id), mask_of(d, id).unwrap()); assert_eq!(m.from, im.key, "made for the file's new pixels"); - let px = image::load_from_memory(&d.images[&m.key].bytes).unwrap().to_rgba8(); + let px = craft_image_codecs::decode(&d.images[&m.key].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(4, 4).0), (0, [0, 0, 200, 255])); } @@ -812,7 +985,24 @@ fn a_live_color_adjustment_recolors_the_image_when_its_masked_pixels_are_missing let NodeKind::Image(im) = &out.kind else { panic!("an image") }; assert_ne!(im.key, image_of(&d, id).key, "the expanded image is recolored"); assert_eq!(Document::color_mask_of(&out), None, "the expanded image has no mask to make again from the recolored pixels"); - let px = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8(); + let px = craft_image_codecs::decode(&d.images[&im.key].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!(px.get_pixel(1, 1).0, WHITE, "the expanded image shows the white"); } @@ -1002,6 +1192,23 @@ fn placing_a_document_brings_the_masked_pixels() { } let [(im, placed)] = found.as_slice() else { panic!("one masked image: {found:?}") }; assert!(placed.made_for(im) && placed.from != m.from, "the image was renamed and the mask follows: {placed:?}"); - let px = image::load_from_memory(&d.images[&placed.key].bytes).unwrap().to_rgba8(); + let px = craft_image_codecs::decode(&d.images[&placed.key].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(4, 4).0), (0, RED)); } diff --git a/crates/engine/src/cmd/addons/image/tests.rs b/crates/engine/src/cmd/addons/image/tests.rs index ae59efad87..23cfb6ad51 100644 --- a/crates/engine/src/cmd/addons/image/tests.rs +++ b/crates/engine/src/cmd/addons/image/tests.rs @@ -21,7 +21,41 @@ fn settings(background: Background) -> Settings { fn png(img: DynamicImage) -> Vec { let mut out = Vec::new(); - img.write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); out } @@ -53,7 +87,23 @@ fn bytes_of(s: &Session, id: NodeId) -> Arc> { } fn pixels(s: &Session, id: NodeId) -> DynamicImage { - image::load_from_memory(&bytes_of(s, id)).unwrap() + craft_image_codecs::decode(&bytes_of(s, id)) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() } fn alpha(img: &DynamicImage, x: u32, y: u32) -> u8 { @@ -164,13 +214,13 @@ fn preview_steps_on_the_same_pixels_decode_them_once() { /// image with an ICC profile comes out as a run on freshly decoded pixels gives it. #[test] fn reused_pixels_keep_their_depth_gray_and_profile() { - use image::{ImageDecoder as _, ImageEncoder as _}; let icc = b"a profile's bytes".to_vec(); let gray16 = ImageBuffer::from_fn(8, 8, |x, y| Luma([if (2..6).contains(&x) && (2..6).contains(&y) { 7_000u16 } else { 61_000 }])); - let mut bytes = Vec::new(); - let mut encoder = image::codecs::png::PngEncoder::new(&mut bytes); - encoder.set_icc_profile(icc.clone()).unwrap(); - DynamicImage::ImageLuma16(gray16).write_with_encoder(encoder).unwrap(); + let raw: Vec = gray16.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(); + let mut cimg = + craft_image_codecs::Image::from_raw(8, 8, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U16, raw).unwrap(); + cimg.meta.icc = Some(icc.clone()); + let bytes = craft_image_codecs::encode(&cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); let decodes = || super::DECODES.with(std::cell::Cell::get); let (mut s, id) = open(&bytes); let start = decodes(); @@ -184,8 +234,8 @@ fn reused_pixels_keep_their_depth_gray_and_profile() { let DynamicImage::ImageLumaA16(out) = pixels(&s, id) else { panic!("16-bit gray with alpha") }; assert_eq!((out.get_pixel(0, 0).0, out.get_pixel(3, 3).0), ([61_000, 0], [7_000, 65_535])); let result = bytes_of(&s, id); - let mut decoder = image::codecs::png::PngDecoder::new(Cursor::new(result.as_slice())).unwrap(); - assert_eq!(decoder.icc_profile().unwrap(), Some(icc)); + let decoded = craft_image_codecs::decode_as(craft_image_codecs::Format::Png, result.as_slice()).unwrap(); + assert_eq!(decoded.meta.icc, Some(icc)); } /// Once the background is cleared, most edge pixels are clear and a second run clears nothing: the @@ -385,16 +435,22 @@ fn a_gray_image_colorized_with_a_process_color_is_refused() { /// The ICC profile the colors are in stays with them. #[test] fn the_color_profile_is_kept() { - use image::{ImageDecoder as _, ImageEncoder as _}; let icc = b"a profile's bytes".to_vec(); - let mut bytes = Vec::new(); - let mut encoder = image::codecs::png::PngEncoder::new(&mut bytes); - encoder.set_icc_profile(icc.clone()).unwrap(); - DynamicImage::ImageRgba8(framed()).write_with_encoder(encoder).unwrap(); + let f = framed(); + let mut cimg = craft_image_codecs::Image::from_raw( + f.width(), + f.height(), + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + f.into_raw(), + ) + .unwrap(); + cimg.meta.icc = Some(icc.clone()); + let bytes = craft_image_codecs::encode(&cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); let blob = ImageBlob::png(bytes); let out = super::clear(&blob, &settings(Background::Edges), None, super::C).unwrap().unwrap(); - let mut decoder = image::codecs::png::PngDecoder::new(Cursor::new(out.blob.bytes.as_slice())).unwrap(); - assert_eq!(decoder.icc_profile().unwrap(), Some(icc)); + let decoded = craft_image_codecs::decode_as(craft_image_codecs::Format::Png, out.blob.bytes.as_slice()).unwrap(); + assert_eq!(decoded.meta.icc, Some(icc)); } /// The resolution the file declares stays with the pixels, so a later Replace or relink sizes the diff --git a/crates/engine/src/cmd/docinfo.rs b/crates/engine/src/cmd/docinfo.rs index b5ac1c13e5..91a45ec4de 100644 --- a/crates/engine/src/cmd/docinfo.rs +++ b/crates/engine/src/cmd/docinfo.rs @@ -1500,9 +1500,41 @@ mod tests { s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap(); let mut bytes = Vec::new(); - image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap()) - .write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap())).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| bytes.extend_from_slice(&__b)) + } + .unwrap(); let image = s .edit("Place", |d, sel| { d.images.insert("gray".into(), vectorcraft_doc::ImageBlob::png(bytes)); @@ -1657,9 +1689,41 @@ mod tests { s.execute("paint.setStroke", &json!({"ids": [word], "none": true})).unwrap(); // A grayscale image colorized with the spot color. let mut bytes = Vec::new(); - image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap()) - .write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap())).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| bytes.extend_from_slice(&__b)) + } + .unwrap(); let image = s .edit("Place", |d, sel| { d.images.insert("gray".into(), vectorcraft_doc::ImageBlob::png(bytes)); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 9ecb5c3984..8cc701c182 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -526,26 +526,34 @@ fn doc_compare(s: &mut Session, p: &Value) -> Result { /// RGBA: a PNG, JPEG, WebP, TIFF or BMP within the allocation an opened image may take. #[cfg(not(target_arch = "wasm32"))] fn compare_image(path: &str) -> Result { - use image::ImageDecoder as _; const C: &str = "document.compare"; let bytes = super::fileio::read_file(path)?; if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(&bytes) { return Err(bad(C, format!("an image of {w} × {h} pixels is too large to draw"))); } - let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().map_err(|e| bad(C, format!("{path}: {e}")))?; - let readable = [image::ImageFormat::Png, image::ImageFormat::Jpeg, image::ImageFormat::WebP, image::ImageFormat::Tiff, image::ImageFormat::Bmp]; - if !reader.format().is_some_and(|f| readable.contains(&f)) { + let format = craft_image_codecs::detect(&bytes); + let readable = [ + craft_image_codecs::Format::Png, + craft_image_codecs::Format::Jpeg, + craft_image_codecs::Format::WebP, + craft_image_codecs::Format::Tiff, + craft_image_codecs::Format::Bmp, + ]; + let Some(format) = format.filter(|f| readable.contains(f)) else { return Err(bad(C, format!("{path}: not a PNG, JPEG, WebP, TIFF or BMP image"))); - } - let mut limits = image::Limits::default(); - limits.max_alloc = Some(vectorcraft_doc::MAX_RASTER_ALLOC); - reader.limits(limits); - let decoder = reader.into_decoder().map_err(|e| bad(C, format!("{path}: {e}")))?; - let (w, h) = decoder.dimensions(); - if decoder.total_bytes() > vectorcraft_doc::MAX_RASTER_ALLOC || u64::from(w) * u64::from(h) * 4 > vectorcraft_doc::MAX_RASTER_ALLOC { - return Err(bad(C, format!("an image of {w} × {h} pixels is too large to draw"))); - } - Ok(image::DynamicImage::from_decoder(decoder).map_err(|e| bad(C, format!("{path}: {e}")))?.to_rgba8()) + }; + let mut opts = craft_image_codecs::DecodeOptions::default(); + opts.limits.max_alloc = vectorcraft_doc::MAX_RASTER_ALLOC; + opts.limits.max_pixels = vectorcraft_doc::MAX_RASTER_ALLOC / 4; + let img = match craft_image_codecs::decode_as_with(format, &bytes, &opts) { + Ok(img) => img, + Err(craft_image_codecs::CodecError::LimitExceeded(_)) => { + return Err(bad(C, "image is too large to draw")); + } + Err(e) => return Err(bad(C, format!("{path}: {e}"))), + }; + let (w, h) = img.dimensions(); + image::RgbaImage::from_raw(w, h, img.to_rgba8()).ok_or_else(|| bad(C, format!("{path}: invalid pixel buffer"))) } #[cfg(target_arch = "wasm32")] diff --git a/crates/engine/src/cmd/fileio/affinity/import.rs b/crates/engine/src/cmd/fileio/affinity/import.rs index 0b0d587d8d..755ad5b07b 100644 --- a/crates/engine/src/cmd/fileio/affinity/import.rs +++ b/crates/engine/src/cmd/fileio/affinity/import.rs @@ -30,13 +30,11 @@ fn preview(name: &str, bytes: &[u8], native: &vectorcraft_affinity::Error) -> Re let p = vectorcraft_affinity::preview(bytes).map_err(|e| err(format!("{native}; its embedded preview can't be read either ({e})")))?; // `raster_doc` normally probes PNG dimensions and keeps its encoded bytes. Verify this // untrusted preview's complete pixels first, so corrupt data cannot create a blank image. - let mut reader = image::ImageReader::with_format(Cursor::new(p.png), image::ImageFormat::Png); - let mut limits = image::Limits::default(); - limits.max_image_width = Some(4096); - limits.max_image_height = Some(4096); - limits.max_alloc = Some(128 << 20); - reader.limits(limits); - let _pixels = reader.decode().map_err(err)?; + let mut opts = craft_image_codecs::DecodeOptions::default(); + opts.limits.max_width = 4096; + opts.limits.max_height = 4096; + opts.limits.max_alloc = 128 << 20; + let _pixels = craft_image_codecs::decode_as_with(craft_image_codecs::Format::Png, &p.png, &opts).map_err(err)?; let d = raster_doc(name, p.png)?; Ok(( d, diff --git a/crates/engine/src/cmd/fileio/affinity/layout.rs b/crates/engine/src/cmd/fileio/affinity/layout.rs index 262f688b13..4f47811c7f 100644 --- a/crates/engine/src/cmd/fileio/affinity/layout.rs +++ b/crates/engine/src/cmd/fileio/affinity/layout.rs @@ -131,10 +131,9 @@ pub(super) fn fit_lines(obj: &mut TextObject, w: f64, h: f64) -> bool { /// RGBA pixels as a PNG file. pub(super) fn png(width: u32, height: u32, rgba: Vec) -> Option> { - let buf = image::RgbaImage::from_raw(width, height, rgba)?; - let mut png = Vec::new(); - buf.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?; - Some(png) + let raw = + craft_image_codecs::Image::from_raw(width, height, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba).ok()?; + craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok() } /// Where a line of `w` starts in a span from 0 to `room` (as a share of `room - w`). diff --git a/crates/engine/src/cmd/fileio/heifread.rs b/crates/engine/src/cmd/fileio/heifread.rs index 4867022ded..df1a2ec24a 100644 --- a/crates/engine/src/cmd/fileio/heifread.rs +++ b/crates/engine/src/cmd/fileio/heifread.rs @@ -1,20 +1,18 @@ -//! HEIC and HEIF images for File › Open and File › Place, decoded with heic-rs when the engine's -//! `heif` feature is on (the default). The image is bounded before decoding and converted to RGBA -//! for the common PNG storage path. A build without the feature still recognizes the files and -//! refuses them with a message. +//! HEIC and HEIF images for File › Open and File › Place, decoded with `craft-heif` when the +//! engine's `heif` feature is on (the default). The image is bounded before decoding and converted +//! to RGBA for the common PNG storage path. A build without the feature still recognizes the files +//! and refuses them with a message. -#[cfg(all(test, feature = "heif"))] -pub(super) use decoder::{active_sps, picture_bytes, sps_signal, sps_size}; #[cfg(feature = "heif")] pub(super) use decoder::{decode, quarter_turned, with_exif}; -/// The brands heic-rs 0.1.4 reads: HEVC-coded images and image sequences (ISO/IEC 23008-12 annex +/// The brands `craft-heif` reads: HEVC-coded images and image sequences (ISO/IEC 23008-12 annex /// B) and the general image and sequence brands. const BRANDS: [&[u8; 4]; 7] = [b"heic", b"heix", b"heim", b"heis", b"hevc", b"mif1", b"msf1"]; /// Recognize a HEIF file by its `ftyp` box: one of [`BRANDS`] as the major brand or a compatible -/// one, and no AVIF brand (`avif`, `avis`), as heic-rs refuses a file that lists one. The box is -/// read as JP2 boxes are ([`super::jp2read::boxes`]): ISO BMFF sizes, the 64-bit one included. +/// one, and no AVIF brand (`avif`, `avis`). The box is read as JP2 boxes are +/// ([`super::jp2read::boxes`]): ISO BMFF sizes, the 64-bit one included. pub(super) fn is_heif(bytes: &[u8]) -> bool { let Some((b"ftyp", ftyp)) = super::jp2read::boxes(bytes).next() else { return false }; let Some(major) = ftyp.get(..4).and_then(|b| <&[u8; 4]>::try_from(b).ok()) else { return false }; @@ -46,582 +44,72 @@ pub(super) fn with_exif(_bytes: &[u8], _read: impl FnOnce(&[u8]) -> Option #[cfg(feature = "heif")] mod decoder { - use heic_rs::context::Context; - use heic_rs::{DecodeOptions, Error, MatrixCoefficients, Nclx, PixelLayout, Range}; + use craft_heif::{Colour, Error, Options}; /// The message for a file that isn't a readable HEIF image. const UNREADABLE: &str = "the HEIC or HEIF file can't be read"; - /// The message for an image sequence, an overlay, an image that isn't HEVC-coded, a grid whose - /// tiles are cropped, turned or mirrored, or an HEVC coding tool the decoder doesn't implement. + /// The message for an image kind that `craft-heif` does not handle. const UNSUPPORTED: &str = "the HEIC or HEIF file holds a kind of image that can't be read"; - /// Decode the primary image within `max_alloc` bytes, counting the decoder's planes, the RGBA - /// output and the copy that rotating or cropping makes, with the container's rotation, mirror + /// Decode the primary image within `max_alloc` bytes, with the container's rotation, mirror, /// and crop applied. An embedded RGB ICC profile, or `nclx` Display P3 primaries with the sRGB - /// curve, is converted to sRGB; other `nclx` values are read as sRGB. A panic inside the - /// decoder is reported as an unreadable file. + /// curve, is converted to sRGB; other `nclx` values are read as sRGB. pub(in super::super) fn decode(bytes: &[u8], max_alloc: u64) -> Result { - crate::guard::catch_panic(|| decode_unguarded(bytes, max_alloc)).unwrap_or_else(|_| Err(UNREADABLE.into())) + let refused = |e: Error| match e { + Error::Unsupported(_) => UNSUPPORTED.to_string(), + _ => UNREADABLE.to_string(), + }; + let info = craft_heif::probe(bytes).map_err(refused)?; + let too_large = || format!("an image of {} × {} pixels is too large to draw", info.coded_width, info.coded_height); + let coded = u64::from(info.coded_width).checked_mul(u64::from(info.coded_height)).ok_or_else(too_large)?; + let shown = u64::from(info.width).checked_mul(u64::from(info.height)).ok_or_else(too_large)?; + if coded == 0 || shown == 0 || coded.checked_mul(17).is_none_or(|n| n > max_alloc) { + return Err(too_large()); + } + let decoded = craft_heif::decode(bytes, &Options { max_pixels: max_alloc / 17, ..Options::default() }).map_err(|e| match e { + Error::Limit(_) => too_large(), + e => refused(e), + })?; + let channels = if decoded.has_alpha { 4usize } else { 3usize }; + let profile = source_profile(decoded.icc.as_deref(), decoded.colour); + let to_u8 = |s: u16| ((u32::from(s) * 255 + 32767) / 65535) as u8; + let mut rgba = Vec::with_capacity(decoded.width as usize * decoded.height as usize * 4); + for px in decoded.data.chunks_exact(channels) { + let a = if decoded.has_alpha { to_u8(px[3]) } else { 255 }; + let [r, g, b] = if let Some(profile) = profile.as_ref() { + let device = [px[0], px[1], px[2]].map(|v| f32::from(v) / 65535.0); + profile + .to_srgb_into(&device, vectorcraft_color::cms::Intent::RelativeColorimetric) + .map(|rgb| rgb.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)) + .unwrap_or_else(|| [to_u8(px[0]), to_u8(px[1]), to_u8(px[2])]) + } else { + [to_u8(px[0]), to_u8(px[1]), to_u8(px[2])] + }; + rgba.extend_from_slice(&[r, g, b, a]); + } + image::RgbaImage::from_raw(decoded.width, decoded.height, rgba).ok_or_else(|| UNREADABLE.into()) } - /// Whether the container's rotations of the primary image add up to an odd number of quarter - /// turns, so its width and height swap. The decoder applies every `irot` the item lists. + /// Whether the container's transforms swap width and height. pub(in super::super) fn quarter_turned(bytes: &[u8]) -> bool { - let turned = || { - let ctx = Context::open(bytes).ok()?; - let props = ctx.props(ctx.meta.primary).ok()?; - let quarters = props.transforms.iter().filter(|t| matches!(t, heic_rs::props::Transform::Rotate(r) if r.swaps_axes())).count(); - Some(quarters % 2 == 1) - }; - crate::guard::catch_panic(turned).ok().flatten().unwrap_or(false) + craft_heif::probe(bytes).ok().is_some_and(|i| (i.width > i.height) != (i.coded_width > i.coded_height)) } /// `read` of the primary image's EXIF block, a TIFF structure inside `bytes`, for its /// resolution tags. pub(in super::super) fn with_exif(bytes: &[u8], read: impl FnOnce(&[u8]) -> Option) -> Option { - let find = || { - let ctx = Context::open(bytes).ok()?; - ctx.exif(ctx.meta.primary).ok().flatten() - }; - crate::guard::catch_panic(find).ok().flatten().and_then(read) + let (exif, _) = craft_heif::read_metadata(bytes).ok()?; + exif.as_deref().and_then(read) } - fn decode_unguarded(bytes: &[u8], max_alloc: u64) -> Result { - let refused = |e: Error| match e { - Error::Unsupported(_) | Error::MissingBox("hvcC" | "meta") => UNSUPPORTED.to_string(), - _ => UNREADABLE.to_string(), - }; - let info = heic_rs::probe(bytes).map_err(refused)?; - let ctx = Context::open(bytes).map_err(refused)?; - if unsupported_items(&ctx).ok_or(UNREADABLE)? { - return Err(UNSUPPORTED.into()); - } - // The stored size, before a crop: the size the decoder holds. - let too_large = || format!("an image of {} × {} pixels is too large to draw", info.coded_width, info.coded_height); - let declared = u64::from(info.coded_width).checked_mul(u64::from(info.coded_height)).ok_or_else(too_large)?; - // A grid is composed at the size its own data gives, which need not match `ispe`. - let grid = grid_pixels(&ctx).ok_or(UNREADABLE)?; - // A single picture is converted at the size its stream gives, which need not match `ispe` - // either. - let coded = declared.max(grid).max(stream_pixels(&ctx).ok_or(UNREADABLE)?); - let shown = u64::from(info.width).checked_mul(u64::from(info.height)).ok_or_else(too_large)?; - // The RGBA output, and a second RGBA image when the decoder rotates, mirrors or crops it, - // which is no larger than the first. - let output = coded.checked_mul(8).ok_or_else(too_large)?; - let pictures = picture_bytes_in(&ctx).ok_or(UNREADABLE)?; - // An alpha grid is composed into a frame of 16-bit planes (at most three samples a pixel), - // and so is the image's grid when it is decoded with a color description of its tiles or - // its stream. A single picture is converted in place. - let composed = if grid > 0 { coded.checked_mul(if info.has_alpha { 12 } else { 6 }).ok_or_else(too_large)? } else { 0 }; - if coded == 0 || shown == 0 || output.checked_add(pictures).and_then(|n| n.checked_add(composed)).is_none_or(|n| n > max_alloc) { - return Err(too_large()); - } - let max_pixels = max_alloc / 4; - let decoded = match tile_nclx(&ctx).or_else(|| stream_nclx(&ctx)) { - Some(nclx) => decode_with_nclx(&ctx, nclx, max_pixels), - None => heic_rs::decode(bytes, &DecodeOptions::default().with_layout(PixelLayout::Rgba8).with_max_pixels(Some(max_pixels))), - } - .map_err(|e| match e { - Error::PixelLimit { .. } | Error::BoxTooLarge { .. } => too_large(), - e => refused(e), - })?; - let mut img = image::RgbaImage::from_raw(decoded.width, decoded.height, decoded.data).ok_or(UNREADABLE)?; - if let Some(profile) = source_profile(&ctx) { - for pixel in img.pixels_mut() { - let [r, g, b, a] = pixel.0; - let device = [r, g, b].map(|v| f32::from(v) / 255.0); - if let Some(rgb) = profile.to_srgb_into(&device, vectorcraft_color::cms::Intent::RelativeColorimetric) { - let [r, g, b] = rgb.map(|v| (v * 255.0).round() as u8); - pixel.0 = [r, g, b, a]; - } - } - } - Ok(img) - } - - /// The primary image and its alpha image, when it has one. - fn primary_and_alpha(ctx: &Context<'_>) -> Option> { - let primary = ctx.meta.primary; - Some(std::iter::once(primary).chain(ctx.alpha_item(primary).ok()?)) - } - - /// Whether the primary image or its alpha image is neither an HEVC-coded item (`hvc1`, `hev1`) - /// nor a grid of them, or is a grid with a tile that carries a crop, rotation or mirror. heic-rs - /// 0.1.4 decodes any item with an `hvcC` whatever its type, and composes a grid from its tiles - /// as coded, without their transforms: an encoder that pads tiles smaller than its coding block - /// (64 × 64 for x265) and crops them back with `clap` gets the wrong pixels. - fn unsupported_items(ctx: &Context<'_>) -> Option { - let hevc = |id: u32| ctx.meta.item(id).is_some_and(|info| info.is_hevc()); - for item in primary_and_alpha(ctx)? { - let Some((_, tiles)) = ctx.grid(item).ok()? else { - if !hevc(item) { - return Some(true); - } - continue; - }; - for tile in tiles { - if !hevc(tile) || !ctx.props(tile).ok()?.transforms.is_empty() { - return Some(true); - } - } - } - Some(false) - } - - /// The pixels of the larger of the primary image's grid and its alpha image's grid, at the - /// output size each grid gives; 0 when neither is a grid. - fn grid_pixels(ctx: &Context<'_>) -> Option { - let mut largest = 0u64; - for item in primary_and_alpha(ctx)? { - if let Some((grid, _)) = ctx.grid(item).ok()? { - largest = largest.max(u64::from(grid.output_width) * u64::from(grid.output_height)); - } - } - Some(largest) - } - - /// The pixels of the larger of the primary image and its alpha image when either is a single - /// picture, at the size of its largest sequence parameter set (before its conformance window); - /// 0 when both are grids. `None` when a size can't be read. - fn stream_pixels(ctx: &Context<'_>) -> Option { - let mut largest = 0u64; - for item in primary_and_alpha(ctx)? { - if ctx.grid(item).ok()?.is_some() { - continue; - } - // An item without `hvcC` isn't decoded: heic-rs refuses the file. - let Some(hvcc) = ctx.props(item).ok()?.hvcc else { continue }; - for nal in hvcc.parameter_sets().into_iter().filter(|nal| nal_type(nal) == Some(SPS)) { - let (width, height, _) = sps_size(nal)?; - largest = largest.max(width.checked_mul(height)?); - } - } - Some(largest) - } - - /// The first tile's `nclx` when the primary image is a grid without an `nclx` of its own and - /// its tiles carry one. heic-rs 0.1.4 converts a grid's samples to RGB with the grid item's - /// `nclx` alone, and with its BT.709 limited-range default when the grid has none - /// (tbraun96/heic-rs#6). - fn tile_nclx(ctx: &Context<'_>) -> Option { - let primary = ctx.meta.primary; - if ctx.props(primary).ok()?.nclx.is_some() { - return None; - } - let (_, tiles) = ctx.grid(primary).ok()??; - ctx.props(*tiles.first()?).ok()?.nclx - } - - /// The color description in the HEVC stream's video usability information (ITU-T H.265 - /// E.2.1) of the primary image, or of its grid's first tile, when neither carries an `nclx` - /// (a file whose only color box is an ICC profile, or one without a color box). heic-rs 0.1.4 - /// reads only the container's `nclx` and otherwise converts with BT.709 limited range. - fn stream_nclx(ctx: &Context<'_>) -> Option { - let primary = ctx.meta.primary; - if ctx.props(primary).ok()?.nclx.is_some() { - return None; - } - let coded = match ctx.grid(primary).ok()? { - Some((_, tiles)) => *tiles.first()?, - None => primary, - }; - let props = ctx.props(coded).ok()?; - if props.nclx.is_some() { - return None; - } - let hvcc = props.hvcc?; - let data = ctx.item_data(coded).ok()?; - let slices = hvcc.split_nals(&data).ok()?; - active_sps(&hvcc.parameter_sets(), &slices).and_then(sps_signal) - } - - /// The SPS the first slice of `slices` uses: the one its PPS names (ITU-T H.265 7.4.3.3.1). - pub(in super::super) fn active_sps<'a>(parameter_sets: &[&'a [u8]], slices: &[&[u8]]) -> Option<&'a [u8]> { - let slice = slices.iter().find(|nal| nal_type(nal).is_some_and(|t| t < 32))?; - let bits = &mut Bits { data: &payload(slice), at: 0 }; - // first_slice_segment_in_pic_flag, no_output_of_prior_pics_flag in an IRAP picture (types 16 - // to 23), slice_pic_parameter_set_id. - bits.skip(1)?; - if nal_type(slice).is_some_and(|t| (16..=23).contains(&t)) { - bits.skip(1)?; - } - let pps_id = bits.exp_golomb()?; - // pps_pic_parameter_set_id, pps_seq_parameter_set_id. - let pps_ids = |nal: &[u8]| { - let bits = &mut Bits { data: &payload(nal), at: 0 }; - Some((bits.exp_golomb()?, bits.exp_golomb()?)) - }; - let sps_id = parameter_sets.iter().filter(|nal| nal_type(nal) == Some(PPS)).find_map(|nal| pps_ids(nal).filter(|(id, _)| *id == pps_id))?.1; - let sps_ids = |nal: &[u8]| { - let rbsp = sps_payload(nal)?; - sps_head(&mut Bits { data: &rbsp, at: 0 }).map(|(_, id, ..)| id) - }; - parameter_sets.iter().copied().find(|nal| sps_ids(nal) == Some(sps_id)) - } - - /// The primary image decoded as heic-rs 0.1.4 decodes it (a grid's tiles one after another), - /// with its samples converted to RGBA with `nclx`, the alpha image applied and the image's - /// rotation, mirror and crop applied. - fn decode_with_nclx(ctx: &Context<'_>, nclx: Nclx, max_pixels: u64) -> heic_rs::Result { - use heic_rs::hevc::Frame; - - fn coded(ctx: &Context<'_>, id: u32) -> heic_rs::Result { - let props = ctx.props(id)?; - let hvcc = props.hvcc.as_ref().ok_or(Error::MissingBox("hvcC"))?; - let data = ctx.item_data(id)?; - let frame = heic_rs::hevc::decode_still(&hvcc.parameter_sets(), &hvcc.split_nals(&data)?)?; - frame.validate()?; - Ok(frame) - } - fn item(ctx: &Context<'_>, id: u32, max_pixels: u64) -> heic_rs::Result { - match ctx.grid(id)? { - Some((grid, tiles)) => { - // The tiles decode in parallel on native, as heic-rs's own decode does. - #[cfg(not(target_arch = "wasm32"))] - let frames = { - use rayon::prelude::*; - tiles.par_iter().map(|&t| coded(ctx, t)).collect::>>()? - }; - #[cfg(target_arch = "wasm32")] - let frames = tiles.iter().map(|&t| coded(ctx, t)).collect::>>()?; - heic_rs::grid::compose(&grid, &frames, max_pixels) - } - None => coded(ctx, id), - } - } - - let primary = ctx.meta.primary; - let props = ctx.props(primary)?; - let frame = item(ctx, primary, max_pixels)?; - let alpha = ctx.alpha_item(primary)?.map(|a| item(ctx, a, max_pixels)).transpose()?; - // `None`: rayon's global pool on native, where heic-rs is built with `parallel`. - let image = heic_rs::color::convert(&frame, alpha.as_ref(), nclx, PixelLayout::Rgba8, max_pixels, None)?; - heic_rs::transform::apply_all(image, &props.transforms) - } - - /// The bytes heic-rs 0.1.4 allocates for the coded pictures of `bytes` it decodes (see - /// [`picture_bytes_in`]); `None` when they can't be read. - #[cfg(test)] - pub(in super::super) fn picture_bytes(bytes: &[u8]) -> Option { - picture_bytes_in(&Context::open(bytes).ok()?) - } - - /// The bytes heic-rs 0.1.4 allocates for the coded pictures it decodes: the primary image's, - /// or each tile of its grid, and its alpha image's the same way. Each picture is sized by the - /// largest of its sequence parameter sets (the size the decoder allocates, rounded up to whole - /// 64-sample coding blocks), not by the container, and takes three sets of 16-bit planes: the - /// picture, a filtered copy and the frame returned. `None` when an item's sizes can't be read. - fn picture_bytes_in(ctx: &Context<'_>) -> Option { - let mut total = 0u64; - for item in primary_and_alpha(ctx)? { - let coded = match ctx.grid(item).ok()? { - Some((_, tiles)) => tiles, - None => vec![item], - }; - for id in coded { - let props = ctx.props(id).ok()?; - // An item without `hvcC` isn't decoded: heic-rs refuses the file. - let Some(hvcc) = props.hvcc else { continue }; - // The slices pick their SPS through the PPS, so the largest one is counted. Every - // SPS must be read. - let mut largest = None; - for nal in hvcc.parameter_sets().into_iter().filter(|nal| nal_type(nal) == Some(SPS)) { - let (width, height, chroma) = sps_size(nal)?; - let blocks = |n: u64| n.div_ceil(64) * 64; - // Bytes a sample position takes in one set of planes: luma and the two chroma - // planes. - let planes = match chroma { - 0 => 2, - 1 => 3, - 2 => 4, - _ => 6, - }; - let picture = blocks(width).checked_mul(blocks(height))?.checked_mul(planes * 3)?; - largest = largest.max(Some(picture)); - } - total = total.checked_add(largest?)?; - } - } - Some(total) - } - - /// The NAL unit type of an HEVC sequence parameter set. - const SPS: u8 = 33; - - /// The type of an HEVC NAL unit, from its header. - fn nal_type(nal: &[u8]) -> Option { - nal.first().map(|b| (b >> 1) & 0x3f) - } - - /// The NAL unit type of an HEVC picture parameter set. - const PPS: u8 = 34; - - /// A NAL unit's payload, without its two-byte header and the emulation prevention bytes (the 03 - /// of 00 00 03), up to its first 4,096 bytes. - fn payload(nal: &[u8]) -> Vec { - let mut rbsp = Vec::with_capacity(256); - let mut zeros = 0; - for &b in nal.get(2..).unwrap_or_default().iter().take(4096) { - if b == 3 && zeros >= 2 { - zeros = 0; - continue; - } - zeros = if b == 0 { zeros + 1 } else { 0 }; - rbsp.push(b); - } - rbsp - } - - /// An SPS NAL unit's [`payload`]; `None` for another NAL unit. - fn sps_payload(nal: &[u8]) -> Option> { - (nal_type(nal) == Some(SPS)).then(|| payload(nal)) - } - - /// The fields of an SPS (ITU-T H.265 7.3.2.2) up to the picture height: - /// `sps_max_sub_layers_minus1`, `sps_seq_parameter_set_id`, the width, the height and - /// `chroma_format_idc`. - fn sps_head(bits: &mut Bits<'_>) -> Option<(u64, u64, u64, u64, u64)> { - // sps_video_parameter_set_id, sps_max_sub_layers_minus1, sps_temporal_id_nesting_flag. - bits.skip(4)?; - let sub_layers = bits.read(3)?; - bits.skip(1)?; - // profile_tier_level (7.3.3): the general profile, tier and level, then the sub-layers'. - bits.skip(96)?; - let mut present = Vec::new(); - for _ in 0..sub_layers { - present.push((bits.read(1)?, bits.read(1)?)); - } - if sub_layers > 0 { - bits.skip(2 * (8 - sub_layers as usize))?; - } - for (profile, level) in present { - bits.skip(88 * profile as usize + 8 * level as usize)?; - } - let id = bits.exp_golomb()?; - let chroma = bits.exp_golomb()?; - if chroma == 3 { - bits.skip(1)?; - } - let width = bits.exp_golomb()?; - let height = bits.exp_golomb()?; - Some((sub_layers, id, width, height, chroma)) - } - - /// The picture width, height and `chroma_format_idc` of an HEVC sequence parameter set NAL - /// unit, before its conformance window; `None` for another NAL unit. - pub(in super::super) fn sps_size(nal: &[u8]) -> Option<(u64, u64, u64)> { - let rbsp = sps_payload(nal)?; - let (_, _, width, height, chroma) = sps_head(&mut Bits { data: &rbsp, at: 0 })?; - Some((width, height, chroma)) - } - - /// The video signal type of an HEVC sequence parameter set NAL unit's VUI (ITU-T H.265 E.2.1) - /// as an `nclx`: the full-range flag and, when the VUI describes them, the color primaries, - /// transfer characteristics and matrix coefficients (otherwise 2, unspecified). `None` when the - /// SPS has no VUI, the VUI has no video signal type, or the SPS can't be read that far. - pub(in super::super) fn sps_signal(nal: &[u8]) -> Option { - let rbsp = sps_payload(nal)?; - let bits = &mut Bits { data: &rbsp, at: 0 }; - let (sub_layers, ..) = sps_head(bits)?; - skip_to_vui(bits, sub_layers)?; - // vui_parameters_present_flag, then aspect_ratio_info_present_flag (an Extended_SAR - // aspect_ratio_idc of 255 adds its 32-bit ratio) and overscan_info_present_flag. - if bits.read(1)? == 0 { - return None; - } - if bits.read(1)? == 1 && bits.read(8)? == 255 { - bits.skip(32)?; - } - if bits.read(1)? == 1 { - bits.skip(1)?; - } - // video_signal_type_present_flag: video_format, video_full_range_flag and the color - // description. - if bits.read(1)? == 0 { - return None; - } - bits.skip(3)?; - let range = if bits.read(1)? == 1 { Range::Full } else { Range::Limited }; - let (primaries, transfer, matrix) = if bits.read(1)? == 1 { (bits.read(8)?, bits.read(8)?, bits.read(8)?) } else { (2, 2, 2) }; - let code = |v: u64| u16::try_from(v).ok(); - let matrix_code = code(matrix)?; - Some(Nclx { primaries: code(primaries)?, transfer: code(transfer)?, matrix: MatrixCoefficients::from_code(matrix_code), matrix_code, range }) - } - - /// Skips the fields of an SPS after [`sps_head`], up to `vui_parameters_present_flag`. - fn skip_to_vui(bits: &mut Bits<'_>, sub_layers: u64) -> Option<()> { - // conformance_window_flag and its four offsets. - if bits.read(1)? == 1 { - for _ in 0..4 { - bits.exp_golomb()?; - } - } - // bit_depth_luma_minus8, bit_depth_chroma_minus8. - bits.exp_golomb()?; - bits.exp_golomb()?; - let poc_bits = bits.exp_golomb()?.checked_add(4).filter(|&n| n <= 16)?; - // sps_sub_layer_ordering_info_present_flag, then three values for each sub-layer given. - let ordered = if bits.read(1)? == 1 { sub_layers + 1 } else { 1 }; - for _ in 0..ordered * 3 { - bits.exp_golomb()?; - } - // The coding and transform block sizes and the transform hierarchy depths. - for _ in 0..6 { - bits.exp_golomb()?; - } - // scaling_list_enabled_flag, sps_scaling_list_data_present_flag. - if bits.read(1)? == 1 && bits.read(1)? == 1 { - skip_scaling_lists(bits)?; - } - // amp_enabled_flag, sample_adaptive_offset_enabled_flag. - bits.skip(2)?; - // pcm_enabled_flag: the PCM sample depths, block sizes and loop filter flag. - if bits.read(1)? == 1 { - bits.skip(8)?; - bits.exp_golomb()?; - bits.exp_golomb()?; - bits.skip(1)?; - } - skip_reference_picture_sets(bits)?; - // long_term_ref_pics_present_flag: each picture's POC bits and used flag. - if bits.read(1)? == 1 { - let count = bits.exp_golomb()?; - if count > 32 { - return None; - } - for _ in 0..count { - bits.skip(poc_bits as usize + 1)?; - } - } - // sps_temporal_mvp_enabled_flag, strong_intra_smoothing_enabled_flag. - bits.skip(2) - } - - /// Skips `scaling_list_data()` (ITU-T H.265 7.3.4). - fn skip_scaling_lists(bits: &mut Bits<'_>) -> Option<()> { - for size in 0..4 { - // The 32 × 32 lists are given for matrices 0 and 3 only. - for _ in 0..if size == 3 { 2 } else { 6 } { - if bits.read(1)? == 0 { - // scaling_list_pred_matrix_id_delta. - bits.exp_golomb()?; - } else { - // scaling_list_dc_coef_minus8, then each scaling_list_delta_coef (se(v) codes, - // as long as ue(v) codes). - if size > 1 { - bits.exp_golomb()?; - } - for _ in 0..if size == 0 { 16 } else { 64 } { - bits.exp_golomb()?; - } - } - } - } - Some(()) - } - - /// Skips `num_short_term_ref_pic_sets` and each `st_ref_pic_set()` (ITU-T H.265 7.3.7) of an - /// SPS. A set predicted from the one before it has one or two flags for each of that set's - /// pictures and one more. - fn skip_reference_picture_sets(bits: &mut Bits<'_>) -> Option<()> { - let sets = bits.exp_golomb()?; - if sets > 64 { - return None; - } - // NumDeltaPocs of each set read so far. - let mut pictures: Vec = Vec::new(); - for index in 0..sets { - let predicted = index != 0 && bits.read(1)? == 1; - let count = if predicted { - // delta_rps_sign, abs_delta_rps_minus1. - bits.skip(1)?; - bits.exp_golomb()?; - let mut count = 0; - for _ in 0..=*pictures.last()? { - // used_by_curr_pic_flag, and use_delta_flag when it is 0. - if bits.read(1)? == 1 || bits.read(1)? == 1 { - count += 1; - } - } - count - } else { - let (negative, positive) = (bits.exp_golomb()?, bits.exp_golomb()?); - if negative > 16 || positive > 16 { - return None; - } - // Each picture's delta_poc_s0_minus1 or delta_poc_s1_minus1 and its used flag. - for _ in 0..negative + positive { - bits.exp_golomb()?; - bits.skip(1)?; - } - negative + positive - }; - pictures.push(count); - } - Some(()) - } - - /// A big-endian bit reader over an RBSP. - struct Bits<'a> { - data: &'a [u8], - at: usize, - } - - impl Bits<'_> { - fn bit(&mut self) -> Option { - let byte = self.data.get(self.at / 8)?; - let bit = (byte >> (7 - self.at % 8)) & 1; - self.at += 1; - Some(u64::from(bit)) - } - - fn read(&mut self, n: u32) -> Option { - (0..n).try_fold(0u64, |v, _| Some(v << 1 | self.bit()?)) - } - - fn skip(&mut self, n: usize) -> Option<()> { - self.at = self.at.checked_add(n)?; - (self.at <= self.data.len() * 8).then_some(()) - } - - /// An unsigned Exp-Golomb code, ue(v), of at most 32 leading zeros. - fn exp_golomb(&mut self) -> Option { - let mut zeros = 0; - while self.bit()? == 0 { - zeros += 1; - if zeros > 32 { - return None; - } - } - Some((1u64 << zeros) - 1 + self.read(zeros)?) - } - } - - /// `nclx` color primaries for Display P3 (SMPTE EG 432-1) and transfer characteristics for - /// the sRGB curve (IEC 61966-2-1), ITU-T H.273. const P3_PRIMARIES: u16 = 12; const SRGB_TRANSFER: u16 = 13; - /// The profile the decoded RGB values are in when it isn't sRGB: the primary item's RGB ICC - /// profile, else Display P3 when its `nclx` names P3 primaries with the sRGB curve. A grid - /// without its own `colr` takes its first tile's, as cameras write it on the tiles. A profile - /// that can't be read, or isn't RGB, is left out and the values are read as sRGB. Without any - /// `colr`, the HEVC stream's color description ([`stream_nclx`]) is read the same way. - fn source_profile(ctx: &Context<'_>) -> Option { + fn source_profile(icc: Option<&[u8]>, colour: Colour) -> Option { use vectorcraft_color::cms::{self, IccProfile, ProfileKind}; - - let id = ctx.meta.primary; - let own = ctx.props(id).ok()?; - let described = |p: &heic_rs::props::ItemProps<'_>| p.icc.is_some() || p.nclx.is_some(); - let tile = || ctx.grid(id).ok().flatten().and_then(|(_, tiles)| tiles.first().and_then(|&t| ctx.props(t).ok())).filter(described); - let props = if described(&own) { Some(own) } else { tile() }; - if let Some(icc) = props.as_ref().and_then(|p| p.icc) { + if let Some(icc) = icc { return IccProfile::from_bytes(None, icc).ok().filter(|p| p.kind == ProfileKind::Rgb); } - let nclx = match props { - Some(props) => props.nclx?, - None => stream_nclx(ctx)?, - }; - (nclx.primaries == P3_PRIMARIES && nclx.transfer == SRGB_TRANSFER).then(|| cms::icc::builtin_rgb(cms::DISPLAY_P3)).flatten() + (colour.primaries == P3_PRIMARIES && colour.transfer == SRGB_TRANSFER).then(|| cms::icc::builtin_rgb(cms::DISPLAY_P3)).flatten() } } diff --git a/crates/engine/src/cmd/fileio/jp2read.rs b/crates/engine/src/cmd/fileio/jp2read.rs index 9e0752c2c5..18e67fafdb 100644 --- a/crates/engine/src/cmd/fileio/jp2read.rs +++ b/crates/engine/src/cmd/fileio/jp2read.rs @@ -1,7 +1,7 @@ //! JPEG 2000 JP2 and codestream images for File › Open and File › Place. The decoded image is //! bounded before allocation and converted to RGBA for the common PNG storage path. -use hayro_jpeg2000::{ColorSpace, DecodeSettings, DecoderContext, Image}; +use craft_image_codecs::{ChannelLayout, CodecError, Format, Limits}; use vectorcraft_color::cms::{IccProfile, Intent}; /// Recognize a JP2 signature box or the start of a raw codestream. The decoder checks the rest. @@ -31,249 +31,65 @@ pub(super) fn boxes(b: &[u8]) -> impl Iterator { }) } -/// The decoder ignores JPX layers and composition and silently uses the last top-level jp2c. -fn unsupported_jpx_content(bytes: &[u8]) -> bool { - fn association_has_content(data: &[u8], depth: usize) -> bool { - if depth >= 16 { - return true; - } - boxes(data).any(|(ty, child)| { - matches!(ty, b"jp2c" | b"jpch" | b"jplh" | b"comp" | b"ftbl") || (ty == b"asoc" && association_has_content(child, depth + 1)) - }) - } - let mut codestreams = 0u8; - for (ty, data) in boxes(bytes) { - match ty { - b"jp2c" => { - codestreams = codestreams.saturating_add(1); - if codestreams > 1 { - return true; - } - } - b"jpch" | b"jplh" | b"comp" | b"ftbl" => return true, - b"asoc" if association_has_content(data, 0) => return true, - _ => {} - } - } - false -} - -/// The largest embedded ICC profile read. -const MAX_PROFILE: usize = 4 * 1024 * 1024; -/// A codestream numbers its tiles 0 to 65,534 (Isot in SOT, ITU-T T.800 A.4.2). -const MAX_TILES: u64 = 65_535; -/// Bytes the decoder keeps for each component of each tile before decoding any of them. -const TILE_COMPONENT_BYTES: u64 = 256; - -/// SIZ follows SOC in the codestream; Lsiz includes its two length bytes. Returns the component -/// count, the image size and the tile count. -fn codestream_size(bytes: &[u8]) -> Option<(u64, u32, u32, u64)> { - let stream = if bytes.starts_with(b"\xff\x4f") { bytes } else { boxes(bytes).find_map(|(ty, data)| (ty == b"jp2c").then_some(data))? }; - if stream.get(..4)? != b"\xff\x4f\xff\x51" { - return None; - } - let length = u16::from_be_bytes(stream.get(4..6)?.try_into().ok()?) as usize; - let count = u16::from_be_bytes(stream.get(40..42)?.try_into().ok()?) as usize; - if count == 0 || length != 38usize.checked_add(count.checked_mul(3)?)? || stream.get(4..4usize.checked_add(length)?)?.len() != length { - return None; - } - let be32 = |range: std::ops::Range| stream.get(range).and_then(|v| v.try_into().ok()).map(u32::from_be_bytes); - let width = be32(8..12)?.checked_sub(be32(16..20)?)?; - let height = be32(12..16)?.checked_sub(be32(20..24)?)?; - // Tiles across and down (T.800 B-5): the grid from the tile offset, in whole tiles. - let tiles = |grid: u32, offset: u32, tile: u32| match (grid.checked_sub(offset), tile) { - (Some(span), 1..) => Some(u64::from(span).div_ceil(u64::from(tile))), - _ => None, - }; - let across = tiles(be32(8..12)?, be32(32..36)?, be32(24..28)?)?; - let down = tiles(be32(12..16)?, be32(36..40)?, be32(28..32)?)?; - Some((count as u64, width, height, across.checked_mul(down)?)) -} - -/// One `jp2h` header with at most one palette, component mapping and channel definition box, so -/// the checks below read the boxes the decoder uses. -fn single_header_boxes(bytes: &[u8]) -> bool { - let mut headers = boxes(bytes).filter(|(ty, _)| *ty == b"jp2h"); - let (Some((_, header)), None) = (headers.next(), headers.next()) else { - return false; - }; - [b"pclr", b"cmap", b"cdef"].iter().all(|kind| boxes(header).filter(|(ty, _)| ty == kind).count() <= 1) -} - -/// The number of channel definitions in a JP2 `cdef` box, `None` without one. Only color channels -/// 1 to n, in any order, followed by at most one opacity channel for the whole image are read; -/// any other layout (premultiplied opacity, opacity before a color, an unassociated channel) gives -/// `Some(0)`, which no image matches. -fn channel_definitions(bytes: &[u8]) -> Option { - if bytes.starts_with(b"\xff\x4f") { - return None; - } - let header = boxes(bytes).find_map(|(ty, data)| (ty == b"jp2h").then_some(data))?; - let cdef = boxes(header).find_map(|(ty, data)| (ty == b"cdef").then_some(data))?; - let count = cdef.get(..2).and_then(|n| n.try_into().ok()).map_or(0, |n: [u8; 2]| usize::from(u16::from_be_bytes(n))); - let Some(entries) = cdef.get(2..).filter(|rest| count > 0 && rest.len() == count * 6) else { - return Some(0); - }; - // (channel, type, association) by channel. - let mut defs: Vec<[u16; 3]> = - entries.as_chunks::<6>().0.iter().map(|&[a, b, c, d, e, f]| [[a, b], [c, d], [e, f]].map(u16::from_be_bytes)).collect(); - defs.sort_unstable(); - let opacity = defs.last().is_some_and(|&[_, kind, association]| kind == 1 && association == 0); - let colors = defs.len() - usize::from(opacity); - let mut seen = vec![false; colors]; - let layout_ok = defs.iter().enumerate().all(|(i, &[channel, kind, association])| { - usize::from(channel) == i - && (i >= colors - || (kind == 0 - && usize::from(association).checked_sub(1).and_then(|slot| seen.get_mut(slot)).is_some_and(|s| !std::mem::replace(s, true)))) - }); - Some(if layout_ok { defs.len() as u64 } else { 0 }) -} - -/// The column count of a JP2 palette (`pclr`), `Ok(None)` without one. A component mapping (`cmap`) -/// beside it needs one entry per column, each naming a codestream component and, when it maps -/// through the palette, a palette column; anything else is `Err`. -fn palette_columns(bytes: &[u8], components: u64) -> Result, ()> { - if bytes.starts_with(b"\xff\x4f") { - return Ok(None); - } - let Some(header) = boxes(bytes).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)) else { - return Ok(None); - }; - let Some(palette) = boxes(header).find_map(|(ty, data)| (ty == b"pclr").then_some(data)) else { - return Ok(None); - }; - let columns = palette.get(2).copied().ok_or(())?; - // Each column's descriptor: unsigned, 1 to 31 bits, as codestream samples are. - let depths = palette.get(3..3 + usize::from(columns)).ok_or(())?; - if columns == 0 || depths.iter().any(|&d| d & 0x80 != 0 || (d & 0x7f) + 1 > 31) { - return Err(()); - } - // Without a mapping the decoder maps every column from the first component. - let Some(mapping) = boxes(header).find_map(|(ty, data)| (ty == b"cmap").then_some(data)) else { - return Ok(Some(u64::from(columns))); - }; - if mapping.len() != usize::from(columns) * 4 { - return Err(()); - } - for &[c0, c1, kind, column] in mapping.as_chunks::<4>().0 { - let valid = u64::from(u16::from_be_bytes([c0, c1])) < components - && match kind { - 0 => true, - 1 => column < columns, - _ => false, - }; - if !valid { - return Err(()); - } - } - Ok(Some(u64::from(columns))) -} - -/// Decode within the raster allocation allowance, counting source samples, RGBA output, and -/// decoder intermediates. The decoder may need multiple full-sized component planes. +/// Decode `bytes` to RGBA, checking memory limits and converting embedded ICC/CMYK color spaces +/// to sRGB via `vectorcraft_color`. pub(super) fn decode(bytes: &[u8], max_alloc: u64) -> Result { - if bytes.starts_with(b"\0\0\0\x0cjP \r\n\x87\n") && unsupported_jpx_content(bytes) { - return Err("the JPEG 2000 file has an unsupported color space or JPX content".into()); - } - if bytes.starts_with(b"\0\0\0\x0cjP \r\n\x87\n") && !single_header_boxes(bytes) { + if !is_jpeg2000(bytes) { return Err("the JPEG 2000 file can't be read".into()); } - let (codestream_channels, declared_w, declared_h, tile_count) = codestream_size(bytes).ok_or("the JPEG 2000 file can't be read")?; - if tile_count == 0 || tile_count > MAX_TILES { - return Err("the JPEG 2000 file can't be read".into()); - } - let declared_pixels = u64::from(declared_w).checked_mul(u64::from(declared_h)); - if declared_w == 0 - || declared_h == 0 - || declared_pixels.and_then(|n| n.checked_mul(codestream_channels)).and_then(|n| n.checked_mul(4)).is_none_or(|n| n > max_alloc) - || tile_count.checked_mul(codestream_channels).and_then(|n| n.checked_mul(TILE_COMPONENT_BYTES)).is_none_or(|n| n > max_alloc) - { - return Err(format!("an image of {declared_w} × {declared_h} pixels is too large to draw")); - } - // The decoder copies an embedded profile (after a 3-byte `colr` header) when it reads the file. - let header = boxes(bytes).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)).unwrap_or_default(); - if boxes(header).any(|(ty, data)| ty == b"colr" && data.len() > MAX_PROFILE + 3) { - return Err("the JPEG 2000 file has an unsupported color space or JPX content".into()); - } - let palette = palette_columns(bytes, codestream_channels).map_err(|()| "the JPEG 2000 file can't be read")?; - // The decoder keeps each palette value in 8 bytes and each row in its own list. - let palette_rows = boxes(header).find_map(|(ty, data)| (ty == b"pclr").then(|| data.get(..2)).flatten()); - if let (Some(columns), Some(&[r0, r1])) = (palette, palette_rows) - && u64::from(u16::from_be_bytes([r0, r1])) * (columns * 8 + 24) > max_alloc - { - return Err(format!("an image of {declared_w} × {declared_h} pixels is too large to draw")); - } - let image = Image::new(bytes, &DecodeSettings::default()).map_err(|_| "the JPEG 2000 file can't be read")?; + let limits = Limits { max_alloc, max_pixels: max_alloc / 4, ..Limits::default() }; + let image = craft_image_codecs::decode_as_with(Format::Jp2, bytes, &limits).map_err(|e| match e { + CodecError::LimitExceeded(_) => "an image is too large to draw".to_string(), + CodecError::Unsupported { .. } => "the JPEG 2000 file has an unsupported color space or JPX content".to_string(), + _ => "the JPEG 2000 file can't be read".to_string(), + })?; let (w, h) = (image.width(), image.height()); - let color = image.color_space(); - let channels = match color { - ColorSpace::Gray => 1, - ColorSpace::RGB => 3, - ColorSpace::CMYK => 4, - ColorSpace::Icc { num_channels: 1 | 3 | 4, profile } if profile.len() <= MAX_PROFILE => color.num_channels(), - _ => return Err("the JPEG 2000 file has an unsupported color space or JPX content".into()), - }; - let stride = u64::from(channels) + u64::from(image.has_alpha()); - // The decoder sizes its output by the palette's columns and writes one channel per mapping - // entry, so the columns, the entries and the output channels must all match. - if palette.is_some_and(|columns| columns != stride) { - return Err("the JPEG 2000 file can't be read".into()); - } - // The decoder reorders the channels by their definitions (`cdef`) and drops any channel without - // one, so a definition is needed for every channel it writes. - if channel_definitions(bytes).is_some_and(|count| count != stride || count != palette.unwrap_or(codestream_channels)) { - return Err("the JPEG 2000 file can't be read".into()); - } - let plane_channels = codestream_channels.max(stride).max(palette.unwrap_or(0)); let too_large = || format!("an image of {w} × {h} pixels is too large to draw"); let pixels = u64::from(w).checked_mul(u64::from(h)).ok_or_else(too_large)?; - let size = pixels.checked_mul(stride).ok_or_else(too_large)?; let rgba_size = pixels.checked_mul(4).ok_or_else(too_large)?; - // hayro 0.3.5 keeps a f32 plane per component, including alpha, and a second - // f32 coefficient plane per component. Palette mapping or channel definitions - // can temporarily clone the component planes. Reserve another 8 bytes per - // pixel for IDWT and code-block scratch while samples and RGBA coexist. - let plane_bytes = pixels.checked_mul(plane_channels).and_then(|n| n.checked_mul(4)).ok_or_else(too_large)?; - let scratch_bytes = plane_bytes.checked_mul(2).and_then(|n| n.checked_add(pixels.checked_mul(8)?)).ok_or_else(too_large)?; - let working = - size.checked_add(rgba_size).and_then(|n| n.checked_add(plane_bytes)).and_then(|n| n.checked_add(scratch_bytes)).ok_or_else(too_large)?; - if w == 0 || h == 0 || working > max_alloc { + if rgba_size > max_alloc { return Err(too_large()); } - let len = usize::try_from(size).map_err(|_| too_large())?; - let mut samples = vec![0; len]; - image.decode_into(&mut samples, &mut DecoderContext::default()).map_err(|_| "the JPEG 2000 file can't be read")?; - let profile = match color { - ColorSpace::Icc { profile, .. } => { - Some(IccProfile::from_bytes(None, profile).map_err(|_| "the JPEG 2000 file has an unsupported color space or JPX content")?) - } - _ => None, + let layout = image.layout(); + let (channels, has_alpha) = match layout { + ChannelLayout::Gray => (1usize, false), + ChannelLayout::GrayA => (1, true), + ChannelLayout::Rgb => (3, false), + ChannelLayout::Rgba => (3, true), + ChannelLayout::Cmyk => (4, false), + ChannelLayout::CmykA => (4, true), + _ => return Err("the JPEG 2000 file has an unsupported color space or JPX content".into()), + }; + let stride = channels + usize::from(has_alpha); + let profile = match image.icc.as_deref() { + Some(icc) => Some(IccProfile::from_bytes(None, icc).map_err(|_| "the JPEG 2000 file has an unsupported color space or JPX content")?), + None => None, }; let cms = vectorcraft_color::cms::active(); let mut rgba = Vec::with_capacity(usize::try_from(rgba_size).map_err(|_| too_large())?); - for sample in samples.chunks_exact(stride as usize) { + for sample in image.data().chunks_exact(stride) { let at = |i: usize| sample.get(i).copied().unwrap_or(0); - let rgb = match (color, profile.as_ref()) { - (ColorSpace::Gray, _) => [at(0); 3], - (ColorSpace::RGB, _) => [at(0), at(1), at(2)], - (ColorSpace::CMYK, _) => { - cms.cmyk_to_srgb([at(0), at(1), at(2), at(3)].map(|v| f32::from(v) / 255.0), false).map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8) + let rgb = if let Some(profile) = profile.as_ref() { + let mut values = [0.0f32; 4]; + for (dst, src) in values.iter_mut().zip(sample.iter().take(channels)) { + *dst = f32::from(*src) / 255.0; } - (ColorSpace::Icc { .. }, Some(profile)) => { - let mut values = [0.0f32; 4]; - for (dst, src) in values.iter_mut().zip(sample.iter().take(usize::from(channels))) { - *dst = f32::from(*src) / 255.0; - } - profile - .to_srgb_into(&values[..usize::from(channels)], Intent::RelativeColorimetric) - .ok_or("the JPEG 2000 file has an unsupported color space or JPX content")? - .map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8) + profile + .to_srgb_into(&values[..channels], Intent::RelativeColorimetric) + .ok_or("the JPEG 2000 file has an unsupported color space or JPX content")? + .map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8) + } else { + match layout { + ChannelLayout::Gray | ChannelLayout::GrayA => [at(0); 3], + ChannelLayout::Rgb | ChannelLayout::Rgba => [at(0), at(1), at(2)], + ChannelLayout::Cmyk | ChannelLayout::CmykA => cms + .cmyk_to_srgb([at(0), at(1), at(2), at(3)].map(|v| f32::from(v) / 255.0), false) + .map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8), + _ => return Err("the JPEG 2000 file has an unsupported color space or JPX content".into()), } - _ => return Err("the JPEG 2000 file has an unsupported color space or JPX content".into()), }; let [r, g, b] = rgb; - rgba.extend_from_slice(&[r, g, b, if image.has_alpha() { at(usize::from(channels)) } else { 255 }]); + rgba.extend_from_slice(&[r, g, b, if has_alpha { at(channels) } else { 255 }]); } image::RgbaImage::from_raw(w, h, rgba).ok_or_else(|| "the JPEG 2000 file can't be read".into()) } diff --git a/crates/engine/src/cmd/fileio/jxlread.rs b/crates/engine/src/cmd/fileio/jxlread.rs index 1d4e3d1382..62b821cf90 100644 --- a/crates/engine/src/cmd/fileio/jxlread.rs +++ b/crates/engine/src/cmd/fileio/jxlread.rs @@ -1,39 +1,15 @@ -//! Reading JPEG XL images (`.jxl`, ISO/IEC 18181) for File › Open and File › Place, with the -//! jxl-oxide decoder: the bare codestream and the ISOBMFF container. The first frame of an -//! animation is read, with the orientation its header gives applied. -//! -//! Colors come back as sRGB whenever the decoder converts them without a color management -//! system: XYB-encoded images, every color space a JPEG XL header names, and embedded ICC -//! profiles that describe one of them. Any other image with an embedded RGB ICC profile comes -//! back with its samples as stored, as PNG and JPEG files with an embedded profile are drawn, and -//! with the profile. Gray images, and images whose profile is not an RGB one, are refused when the -//! decoder cannot convert their ICC profile. 16-bit and floating-point samples become 8 bits, alpha comes back straight, -//! and CMYK images are refused. The file is untrusted: the decoder is given only a container's -//! image boxes, the image's size is checked from its header before any pixels are decoded, and the -//! decoder's image buffers are capped. +//! Reading JPEG XL images (`.jxl`, ISO/IEC 18181) for File › Open and File › Place, with +//! `craft-jxl`: the bare codestream and the ISOBMFF container. The first frame of an animation is +//! read, with the orientation its header gives applied. -use jxl_color::ColorTransform; -use jxl_oxide::color::{ColourEncoding, TransferFunction}; -use jxl_oxide::{AllocTracker, ColorEncodingWithProfile, EnumColourEncoding, HdrType, InitializeResult, JxlImage, NullCms, RenderingIntent}; +use craft_jxl::{DecodeLimits, Error as JxlError, Layout}; /// A bare JPEG XL codestream starts with these bytes. const CODESTREAM: [u8; 2] = [0xff, 0x0a]; /// The signature box an ISOBMFF JPEG XL container starts with. const CONTAINER: [u8; 12] = [0, 0, 0, 0x0c, b'J', b'X', b'L', b' ', 0x0d, 0x0a, 0x87, 0x0a]; -/// How many bytes the decoder is given first to read the header. Each later try gives it twice as -/// many bytes, and each try decodes the embedded ICC profile from its start again. -const HEAD: usize = 4096; -/// The most the decoder's buffers may take while it reads the header. Its `AllocTracker` counts the -/// image buffers only: an embedded ICC profile is decoded into buffers of its own, which jxl-color -/// limits to 256 MiB. +/// Buffer allowance for container box filtering. const HEADER_BUFFERS: usize = 16 << 20; -/// The most the decoder's buffers may take for the pixels: this many times the image's size as -/// RGBA, plus [`HEADER_BUFFERS`], and never more than the `max_alloc` of [`decode`], the limit the -/// `image` crate's decoders get in `raster_image`. The decoder keeps each channel as 32-bit -/// samples: a lossless 16-bit RGBA image of 1024 × 768 pixels took 12 times its size as RGBA. -const DECODER_BUFFERS: u64 = 16; - -const TRUNCATED: &str = "the JPEG XL file is cut short"; /// Is `bytes` a JPEG XL image (a bare codestream or a container)? pub fn is_jxl(bytes: &[u8]) -> bool { @@ -46,134 +22,48 @@ pub(crate) fn oriented_resolution(ppi: Option<(f64, f64)>, orientation: u32) -> } /// The first frame of a JPEG XL image as straight RGBA, with the embedded ICC profile its colors -/// are in when they are not converted to sRGB ([`output_profile`]), and the header orientation. -/// Fails, without decoding the -/// pixels, when the image would take more than `max_alloc` bytes as RGBA. The image is also too -/// large to draw when the decoder's buffers for its pixels need more than they are allowed. A -/// container whose selected boxes exceed `max_alloc` or [`HEADER_BUFFERS`], whichever is greater, -/// is refused with "the JPEG XL container is too large to read". +/// are in when they are not converted to sRGB, and the header orientation. pub fn decode(bytes: &[u8], max_alloc: u64) -> Result<(image::RgbaImage, Option>, u32), String> { let pixel_boxes = pixel_boxes(bytes, max_alloc.max(HEADER_BUFFERS as u64))?; let bytes = pixel_boxes.as_deref().unwrap_or(bytes); - // The decoder reads the header first, with buffers for the header alone. - let (head, _) = header(bytes, HEADER_BUFFERS, None)?; - let (w, h) = (head.width(), head.height()); - let rgba = u64::from(w) * u64::from(h) * 4; - if rgba > max_alloc { + let limits = DecodeLimits { max_pixels: max_alloc / 4, max_tracked_bytes: Some(max_alloc), max_input_bytes: usize::MAX }; + let decoded = craft_jxl::decode(bytes, limits).map_err(|e| match e { + JxlError::PixelLimitExceeded { width, height, .. } => too_large(width, height), + JxlError::LimitExceeded(msg) => format!("an image is too large to draw: {msg}"), + JxlError::Unsupported(msg) if msg.contains("CMYK") => "CMYK JPEG XL images can't be read".into(), + other => unreadable(other), + })?; + let (w, h) = (decoded.width, decoded.height); + if u64::from(w).saturating_mul(u64::from(h)).saturating_mul(4) > max_alloc { return Err(too_large(w, h)); } - if head.pixel_format().has_black() { - return Err("CMYK JPEG XL images can't be read".into()); - } - // Then it reads the file again until the first frame is loaded, with buffers for the pixels. - let budget = rgba.saturating_mul(DECODER_BUFFERS).saturating_add(HEADER_BUFFERS as u64).min(max_alloc); - let budget = usize::try_from(budget).unwrap_or(usize::MAX); - let size = Some((w, h)); - let (mut image, mut at) = header(bytes, budget, size)?; - let mut end = at; - while image.num_loaded_keyframes() == 0 { - if end == bytes.len() { - return Err(TRUNCATED.into()); + let profile = if !decoded.xyb_encoded && decoded.metadata.icc.as_deref() == Some(decoded.rendered_icc.as_slice()) { + if matches!(decoded.layout, Layout::Gray | Layout::GrayAlpha) { + return Err(unreadable("unsupported grayscale ICC profile")); } - end = end.saturating_mul(2).max(HEAD).min(bytes.len()); - at += image.feed_bytes(&bytes[at..end]).map_err(|e| failed(e, size))?; - } - let metadata = &image.image_header().metadata; - let associated = metadata.alpha().and_then(|i| metadata.ec_info.get(i)).and_then(|ec| ec.alpha_associated()) == Some(true); - let intent = RenderingIntent::Relative; - let srgb = if metadata.grayscale() { EnumColourEncoding::gray_srgb(intent) } else { EnumColourEncoding::srgb(intent) }; - let profile = output_profile(metadata.xyb_encoded, metadata.grayscale(), image.original_icc())?; - let orientation = metadata.orientation; - // Premultiplied colors are divided by alpha in the encoding they are stored in, and converted - // to sRGB after that. XYB-encoded images come from the decoder in linear sRGB (tone mapped when - // they are HDR), which the sRGB transfer curve alone turns into sRGB. - let (request, convert) = match (to_srgb_without_cms(metadata.xyb_encoded, image.original_icc()), associated) { - (false, _) => (None, None), - (true, false) => (Some(srgb), None), - (true, true) if metadata.xyb_encoded => (Some(EnumColourEncoding { tf: TransferFunction::Linear, ..srgb }), Some(ToSrgb::Curve)), - (true, true) => { - let stored = match (&metadata.colour_encoding, image.original_icc()) { - (ColourEncoding::Enum(e), _) => ColorEncodingWithProfile::new(e.clone()), - (_, Some(icc)) => ColorEncodingWithProfile::with_icc(icc).map_err(unreadable)?, - (_, None) => return Err(unreadable("no color encoding")), - }; - let mut builder = ColorTransform::builder(); - builder.from_pq(image.hdr_type() == Some(HdrType::Pq)); - let to = ColorEncodingWithProfile::new(srgb); - let t = builder.build(&stored, &to, &metadata.opsin_inverse_matrix, &metadata.tone_mapping, &NullCms).map_err(unreadable)?; - (None, Some(ToSrgb::Transform(t))) + if decoded.rendered_icc.get(16..20) != Some(b"RGB ") { + return Err(unreadable("unsupported ICC profile color space")); } + Some(decoded.rendered_icc) + } else { + None }; - if let Some(encoding) = request { - image.request_color_encoding(encoding); - } - let render = image.render_frame(0).map_err(|e| failed(e, size))?; - let mut stream = render.stream(); - let channels = stream.channels() as usize; - if !(1..=4).contains(&channels) { - return Err(unreadable(format!("{channels} channels"))); - } - let mut out = image::RgbaImage::new(stream.width(), stream.height()); - let width = out.width() as usize; - let mut row = vec![0f32; width * channels]; - let mut colors = [vec![0f32; width], vec![0f32; width], vec![0f32; width]]; - for line in out.chunks_exact_mut((width * 4).max(4)) { - if stream.write_to_buffer(&mut row) != row.len() { - return Err(TRUNCATED.into()); - } - to_rgba(&row, channels, associated, convert.as_ref(), &mut colors, line)?; - } - Ok((out, profile, orientation)) -} - -/// How colors whose alpha was divided out become sRGB. -pub(crate) enum ToSrgb { - /// A conversion from the encoding the colors are stored in. - Transform(ColorTransform), - /// The sRGB transfer curve, for colors in linear sRGB. - Curve, -} - -/// One row of samples, `channels` to a pixel (gray or RGB, then alpha when there are 2 or 4), as -/// straight RGBA bytes in `out`: colors divided by alpha when it is `associated`, then converted -/// with `convert`. `colors` holds a row of red, green and blue; a gray sample goes into all three, -/// as jxl-render's `clone_gray` does before its own conversions. -pub(crate) fn to_rgba( - row: &[f32], - channels: usize, - associated: bool, - convert: Option<&ToSrgb>, - colors: &mut [Vec; 3], - out: &mut [u8], -) -> Result<(), String> { - let alpha = |s: &[f32]| if matches!(channels, 2 | 4) { s.last().map_or(1.0, |a| a.clamp(0.0, 1.0)) } else { 1.0 }; + let channels = decoded.layout.channels(); let gray = channels < 3; - for (x, s) in row.chunks_exact(channels).enumerate() { - let a = alpha(s); - for (i, plane) in colors.iter_mut().enumerate() { - let v = s.get(if gray { 0 } else { i }).copied().unwrap_or(0.0); - if let Some(c) = plane.get_mut(x) { - *c = if associated && a > 0.0 { v / a } else { v }; - } - } + let has_alpha = decoded.layout.has_alpha(); + let mut out = image::RgbaImage::new(w, h); + for (dst, src) in out.chunks_exact_mut(4).zip(decoded.pixels.chunks_exact(channels)) { + let a = if has_alpha { src[channels - 1].clamp(0.0, 1.0) } else { 1.0 }; + let unpremul = |v: f32| if decoded.pixels_premultiplied && a > 0.0 { v / a } else { v }; + let rgb = if gray { + let v = byte(unpremul(src[0])); + [v, v, v] + } else { + [byte(unpremul(src[0])), byte(unpremul(src[1])), byte(unpremul(src[2]))] + }; + dst.copy_from_slice(&[rgb[0], rgb[1], rgb[2], byte(a)]); } - // The conversion leaves gray in the first row when it gives one channel. - let gray = match convert { - Some(ToSrgb::Transform(t)) => { - let mut planes: Vec<&mut [f32]> = colors.iter_mut().map(Vec::as_mut_slice).collect(); - t.run(&mut planes).map_err(unreadable)? < 3 - } - Some(ToSrgb::Curve) => { - colors.iter_mut().flatten().for_each(|v| *v = if *v <= 0.003_130_8 { *v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }); - gray - } - None => gray, - }; - for (x, (px, s)) in out.as_chunks_mut::<4>().0.iter_mut().zip(row.chunks_exact(channels)).enumerate() { - let c = |i: usize| colors.get(if gray { 0 } else { i }).and_then(|p| p.get(x)).copied().unwrap_or(0.0); - *px = [byte(c(0)), byte(c(1)), byte(c(2)), byte(alpha(s))]; - } - Ok(()) + Ok((out, profile, decoded.source_orientation)) } /// A container's signature and the boxes the decoder reads pixels from (`ftyp`, `jxll`, `jxlc` and @@ -210,56 +100,6 @@ pub(super) fn pixel_boxes(bytes: &[u8], max_copy: u64) -> Result> Ok(Some(out)) } -/// A decoder whose buffers may take `buffers` bytes, given as few of `bytes` as it needs to read -/// the header → (the decoder, how many bytes it took). `size` is the image's size when it is -/// known, for the error when the buffers need more ([`failed`]). -fn header(bytes: &[u8], buffers: usize, size: Option<(u32, u32)>) -> Result<(JxlImage, usize), String> { - let mut uninit = JxlImage::builder().alloc_tracker(AllocTracker::with_limit(buffers)).build_uninit(); - let (mut at, mut end) = (0, 0usize); - loop { - end = end.saturating_mul(2).max(HEAD).min(bytes.len()); - at += uninit.feed_bytes(&bytes[at..end]).map_err(|e| failed(e, size))?; - match uninit.try_init().map_err(|e| failed(e, size))? { - InitializeResult::Initialized(image) => return Ok((image, at)), - InitializeResult::NeedMoreData(_) if end == bytes.len() => return Err(TRUNCATED.into()), - InitializeResult::NeedMoreData(more) => uninit = more, - } - } -} - -/// Does the decoder convert to sRGB without a color management system? It does for XYB-encoded -/// images and the color spaces a header names; for an embedded ICC profile, only when the profile -/// describes one of those. -fn to_srgb_without_cms(xyb: bool, icc: Option<&[u8]>) -> bool { - xyb || icc.is_none_or(|icc| ColorEncodingWithProfile::with_icc(icc).is_ok_and(|p| p.icc_profile().is_empty())) -} - -/// The embedded RGB profile when the decoder leaves colors in it. Gray colors without a -/// conversion to sRGB cannot be stored as RGB without changing their profile, and neither can -/// colors left in a profile that is not an RGB one. -pub(crate) fn output_profile(xyb: bool, grayscale: bool, icc: Option<&[u8]>) -> Result>, String> { - let converts = to_srgb_without_cms(xyb, icc); - if grayscale && !converts { - return Err(unreadable("unsupported grayscale ICC profile")); - } - if !converts && icc.and_then(|icc| icc.get(16..20)) != Some(b"RGB ") { - return Err(unreadable("unsupported ICC profile color space")); - } - Ok(icc.filter(|_| !converts).map(<[u8]>::to_vec)) -} - -/// The decoder's error `e` as a message. When the decoder's buffers needed more than they were -/// allowed and the image's `size` is known, the image is too large to draw. Otherwise the file -/// can't be read. -fn failed(e: Box, size: Option<(u32, u32)>) -> String { - let first: &(dyn std::error::Error + 'static) = &*e; - let out_of_memory = std::iter::successors(Some(first), |c| c.source()).any(|c| c.is::()); - match size { - Some((w, h)) if out_of_memory => too_large(w, h), - _ => unreadable(e), - } -} - fn too_large(w: u32, h: u32) -> String { format!("an image of {w} × {h} pixels is too large to draw") } diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index bb9dc3711a..d0f5121f05 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -131,7 +131,7 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> { if super::heifread::is_heif(bytes) { return format("heif"); } - if let Some(f) = image::guess_format(bytes).ok().and_then(image_format) { + if let Some(f) = craft_image_codecs::detect(bytes).and_then(image_format) { return Some(f); } // A version 2 PICT is known by its version opcodes after the picture's frame, at byte 522 of a @@ -157,9 +157,28 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> { by_name } -/// The readable raster format behind an `image` crate format. -fn image_format(f: image::ImageFormat) -> Option<&'static Format> { - f.extensions_str().iter().find_map(|e| format(e)).filter(|f| f.read && f.raster) +/// The readable raster format behind a `craft_image_codecs` format. +fn image_format(f: craft_image_codecs::Format) -> Option<&'static Format> { + let ext = match f { + craft_image_codecs::Format::Png => "png", + craft_image_codecs::Format::Jpeg => "jpg", + craft_image_codecs::Format::Gif => "gif", + craft_image_codecs::Format::WebP => "webp", + craft_image_codecs::Format::Tiff => "tiff", + craft_image_codecs::Format::Bmp => "bmp", + craft_image_codecs::Format::Tga => "tga", + craft_image_codecs::Format::Ico => "ico", + craft_image_codecs::Format::Qoi => "qoi", + craft_image_codecs::Format::Hdr => "hdr", + craft_image_codecs::Format::OpenExr => "exr", + craft_image_codecs::Format::Avif => "avif", + craft_image_codecs::Format::Jxl => "jxl", + craft_image_codecs::Format::Heif => "heic", + craft_image_codecs::Format::Jp2 => "jp2", + craft_image_codecs::Format::Psd => "psd", + _ => return None, + }; + format(ext).filter(|f| f.read && f.raster) } /// Why a file carrying editing data (an SVG or PDF saved with Preserve Editing) opened as plain @@ -823,16 +842,12 @@ pub(crate) use vectorcraft_doc::MAX_RASTER_ALLOC; /// says so; the pixels aren't read): Open, Place and the Links panel say it ([`size_note`], #1479). /// `None` for images within the allowance, and for bytes that aren't an image. pub(crate) fn too_large_note(bytes: &[u8]) -> Option { - use image::ImageDecoder as _; if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) { return Some(format!("an image of {w} × {h} pixels is too large to draw")); } - let d = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_decoder().ok()?; - let (w, h) = d.dimensions(); - // The allowance also counts the pixels as RGBA: an image of fewer than 4 bytes a pixel (gray, - // gray with alpha, RGB) takes more than the decoder counts (#1717). + let (w, h) = craft_image_codecs::probe_size(bytes).ok().or_else(|| ImageBlob::new("", bytes.to_vec()).header_size())?; let rgba_over = u64::from(w) * u64::from(h) > MAX_RASTER_ALLOC / 4; - (rgba_over || d.total_bytes() > MAX_RASTER_ALLOC).then(|| format!("an image of {w} × {h} pixels is too large to draw")) + rgba_over.then(|| format!("an image of {w} × {h} pixels is too large to draw")) } /// What Open, Place and the Links panel say of encoded image `bytes` that [`too_large_note`] is @@ -842,7 +857,7 @@ pub(crate) fn too_large_note(bytes: &[u8]) -> Option { pub(crate) fn size_note(bytes: &[u8]) -> Option { let note = too_large_note(bytes)?; let Some(drawn) = vectorcraft_render::reduced_size(bytes) else { return Some(note) }; - let (w, h) = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_dimensions().ok()?; + let (w, h) = craft_image_codecs::probe_size(bytes).ok().or_else(|| ImageBlob::new("", bytes.to_vec()).header_size())?; (drawn != (w, h)).then(|| format!("an image of {w} × {h} pixels is shown at reduced size")) } @@ -898,17 +913,15 @@ pub fn raster_image(bytes: &[u8]) -> Result { if super::pxrread::is_pxr(bytes) { return as_png(super::pxrread::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?, None, ppi); } - let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(err)?; - if reader.format().is_none() && super::tgaread::is_targa(bytes) { - reader.set_format(image::ImageFormat::Tga); - } - if reader.format().is_none() && super::pcxread::is_pcx(bytes) { + let detected = craft_image_codecs::detect(bytes); + let kind = if detected.is_none() && super::tgaread::is_targa(bytes) { + Some(craft_image_codecs::Format::Tga) + } else if detected.is_none() && super::pcxread::is_pcx(bytes) { return as_png(super::pcxread::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?, None, ppi); - } - let mut limits = image::Limits::default(); - limits.max_alloc = Some(MAX_RASTER_ALLOC); - reader.limits(limits); - let kind = reader.format().ok_or_else(|| err("not an image VectorCraft reads (see document.formats)"))?; + } else { + detected + }; + let kind = kind.ok_or_else(|| err("not an image VectorCraft reads (see document.formats)"))?; let f = image_format(kind).ok_or_else(|| err(format!("{kind:?} images can't be opened (see document.formats)")))?; // A photo whose EXIF orientation turns or flips it (a camera held upright) is stored as it is // seen, so it places the way it was taken (#4284); the others keep their own bytes. @@ -929,7 +942,10 @@ pub fn raster_image(bytes: &[u8]) -> Result { _ => None, }; if let Some(kept) = kept { - let (width, height) = reader.into_dimensions().map_err(err)?; + let (width, height) = craft_image_codecs::probe_size(bytes) + .ok() + .or_else(|| ImageBlob::new("", bytes.to_vec()).header_size()) + .ok_or_else(|| err("could not read image dimensions"))?; return stored(kept, f.mime, (width, height), ppi); } let extra_samples = || { @@ -943,21 +959,49 @@ pub fn raster_image(bytes: &[u8]) -> Result { None => match (f.id == "tiff").then(|| vectorcraft_doc::cmyk::group3_tiff_rgba(bytes)).flatten() { Some(read) => image::DynamicImage::ImageRgba8(read.map_err(err)?), None => { - use image::ImageDecoder as _; - let mut decoder = reader.into_decoder().map_err(err)?; - // The allowance counts the decoded samples and the RGBA pixels they become (#1717). - let (w, h) = decoder.dimensions(); - if decoder.total_bytes() > MAX_RASTER_ALLOC || u64::from(w) * u64::from(h) * 4 > MAX_RASTER_ALLOC { - return Err(err(format!("an image of {w} × {h} pixels is too large to draw"))); - } - // A profile the decoder can't read leaves the image without one. The image decoder - // reads a TIFF's tags within the size of its pixels, so a small TIFF's profile is - // read by the TIFF decoder itself. + let mut opts = craft_image_codecs::DecodeOptions::default(); + opts.limits.max_alloc = MAX_RASTER_ALLOC; + opts.limits.max_pixels = MAX_RASTER_ALLOC / 4; + opts.keep_orientation = true; + let decoded = craft_image_codecs::decode_as_with(kind, bytes, &opts).map_err(|e| match e { + craft_image_codecs::CodecError::LimitExceeded(_) => err("image is too large to draw"), + _ => err(e), + })?; + let (w, h) = decoded.dimensions(); icc = match f.id { "tiff" => vectorcraft_doc::cmyk::tiff_icc_profile(bytes), - _ => decoder.icc_profile().ok().flatten(), + _ => decoded.icc.clone(), }; - image::DynamicImage::from_decoder(decoder).map_err(err)? + match (decoded.layout(), decoded.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => image::DynamicImage::ImageLuma8( + image::GrayImage::from_raw(w, h, decoded.into_data()).ok_or_else(|| err("invalid gray buffer"))?, + ), + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => image::DynamicImage::ImageLumaA8( + image::GrayAlphaImage::from_raw(w, h, decoded.into_data()).ok_or_else(|| err("invalid gray alpha buffer"))?, + ), + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(w, h, decoded.into_data()).ok_or_else(|| err("invalid rgb buffer"))?) + } + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U16) => { + let s = decoded.to_u16_samples().ok_or_else(|| err("invalid gray16 buffer"))?; + image::DynamicImage::ImageLuma16(image::ImageBuffer::from_raw(w, h, s).ok_or_else(|| err("invalid gray16 buffer"))?) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U16) => { + let s = decoded.to_u16_samples().ok_or_else(|| err("invalid graya16 buffer"))?; + image::DynamicImage::ImageLumaA16(image::ImageBuffer::from_raw(w, h, s).ok_or_else(|| err("invalid graya16 buffer"))?) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U16) => { + let s = decoded.to_u16_samples().ok_or_else(|| err("invalid rgb16 buffer"))?; + image::DynamicImage::ImageRgb16(image::ImageBuffer::from_raw(w, h, s).ok_or_else(|| err("invalid rgb16 buffer"))?) + } + (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U16) => { + let s = decoded.to_u16_samples().ok_or_else(|| err("invalid rgba16 buffer"))?; + image::DynamicImage::ImageRgba16(image::ImageBuffer::from_raw(w, h, s).ok_or_else(|| err("invalid rgba16 buffer"))?) + } + _ => image::DynamicImage::ImageRgba8( + image::RgbaImage::from_raw(w, h, decoded.to_rgba8()).ok_or_else(|| err("invalid rgba buffer"))?, + ), + } } }, }; @@ -987,15 +1031,63 @@ fn png_takes_icc(img: &image::DynamicImage, icc: &[u8]) -> bool { /// `img` stored as a PNG that keeps the file's resolution and carries `icc`, the ICC profile its /// colors are in. `img` has samples a PNG holds: 8 or 16 bits of gray or RGB, with or without alpha. pub(super) fn as_png(img: impl Into, icc: Option>, ppi: Option<(f64, f64)>) -> Result { - use image::ImageEncoder as _; + use image::DynamicImage as D; let img: image::DynamicImage = img.into(); let size = (img.width(), img.height()); - let mut png = Vec::new(); - let mut encoder = image::codecs::png::PngEncoder::new(&mut png); - if let Some(icc) = icc { - encoder.set_icc_profile(icc).map_err(err)?; + let (w, h) = size; + let u16_bytes = |v: Vec| v.into_iter().flat_map(u16::to_ne_bytes).collect::>(); + let raw = match img { + D::ImageLuma8(b) => { + craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()) + } + D::ImageLumaA8(b) => { + craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()) + } + D::ImageRgb8(b) => { + craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()) + } + D::ImageRgba8(b) => { + craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()) + } + D::ImageLuma16(b) => craft_image_codecs::Image::from_raw( + w, + h, + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + u16_bytes(b.into_raw()), + ), + D::ImageLumaA16(b) => craft_image_codecs::Image::from_raw( + w, + h, + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + u16_bytes(b.into_raw()), + ), + D::ImageRgb16(b) => craft_image_codecs::Image::from_raw( + w, + h, + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + u16_bytes(b.into_raw()), + ), + D::ImageRgba16(b) => craft_image_codecs::Image::from_raw( + w, + h, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + u16_bytes(b.into_raw()), + ), + other => craft_image_codecs::Image::from_raw( + w, + h, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + other.into_rgba8().into_raw(), + ), } - img.write_with_encoder(encoder).map_err(err)?; + .map_err(err)? + .with_icc(icc); + let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).map_err(err)?; let png = match ppi { Some(r) => super::ppi::with_png_resolution(&png, r), None => png, @@ -1029,12 +1121,10 @@ pub fn texture_image(bytes: &[u8]) -> Result { LoadedTexture::from_rgba(inks.width, inks.height, &rgba) } None => { - let mut reader = image::ImageReader::new(Cursor::new(blob.bytes.as_slice())).with_guessed_format().map_err(err)?; - let mut limits = image::Limits::default(); - limits.max_alloc = Some(MAX_RASTER_ALLOC); - reader.limits(limits); - let img = reader.decode().map_err(err)?.to_rgba8(); - LoadedTexture::from_rgba(img.width(), img.height(), img.as_raw()) + let mut opts = craft_image_codecs::DecodeOptions::default(); + opts.limits.max_alloc = MAX_RASTER_ALLOC; + let img = craft_image_codecs::decode_with(&blob.bytes, &opts).map_err(err)?; + LoadedTexture::from_rgba(img.width(), img.height(), &img.to_rgba8()) } }; texture.and_then(|t| t.to_stored()).ok_or_else(|| err("the image can't be read as a texture")) diff --git a/crates/engine/src/cmd/fileio/pngtext.rs b/crates/engine/src/cmd/fileio/pngtext.rs index 94a30d13f0..798c59d0ac 100644 --- a/crates/engine/src/cmd/fileio/pngtext.rs +++ b/crates/engine/src/cmd/fileio/pngtext.rs @@ -39,7 +39,23 @@ mod tests { let out = with_text(png.clone(), &[("Title", "Café".into()), ("Author", "Łukasz".into()), ("bad\u{1}", "x".into())]); assert_eq!(text(&out), [("Title".to_string(), "Café".to_string()), ("Author".into(), "Łukasz".into())]); // Still a PNG every decoder reads (the CRCs check out). - let img = image::load_from_memory(&out).unwrap(); + let img = craft_image_codecs::decode(&out) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap(); assert_eq!((img.width(), img.height()), (2, 1)); assert_eq!(with_text(b"not a png".to_vec(), &[("Title", "x".into())]), b"not a png"); assert_eq!(with_text(png.clone(), &[]), png); diff --git a/crates/engine/src/cmd/fileio/ppi.rs b/crates/engine/src/cmd/fileio/ppi.rs index 6998d86b28..06c995751e 100644 --- a/crates/engine/src/cmd/fileio/ppi.rs +++ b/crates/engine/src/cmd/fileio/ppi.rs @@ -257,7 +257,41 @@ mod tests { fn png_of(w: u32, h: u32) -> Vec { let mut out = Vec::new(); - image::RgbaImage::new(w, h).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::new(w, h)).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); out } @@ -274,14 +308,64 @@ mod tests { let again = with_png_resolution(&tagged, (72.0, 72.0)); assert!(close(resolution(&again).unwrap(), (72.0, 72.0)), "replaced, not duplicated"); assert_eq!(again.len(), tagged.len()); - let img = image::load_from_memory(&again).unwrap(); + let img = craft_image_codecs::decode(&again) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap(); assert_eq!((img.width(), img.height()), (4, 3)); } #[test] fn jpeg_jfif_density_in_dpi_and_dpcm() { let mut jpg = Vec::new(); - image::RgbImage::new(2, 2).write_to(&mut std::io::Cursor::new(&mut jpg), image::ImageFormat::Jpeg).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbImage::new(2, 2)).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Jpeg, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| jpg.extend_from_slice(&__b)) + } + .unwrap(); // The encoder writes JFIF with units 0 (aspect only). assert_eq!(resolution(&jpg), None); let jfif = jpg.windows(5).position(|w| w == b"JFIF\0").unwrap(); @@ -345,7 +429,41 @@ mod tests { #[test] fn bmp_pixels_per_metre() { let mut bmp = Vec::new(); - image::RgbImage::new(2, 2).write_to(&mut std::io::Cursor::new(&mut bmp), image::ImageFormat::Bmp).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbImage::new(2, 2)).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Bmp, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| bmp.extend_from_slice(&__b)) + } + .unwrap(); bmp[38..42].copy_from_slice(&11811u32.to_le_bytes()); bmp[42..46].copy_from_slice(&11811u32.to_le_bytes()); assert!(close(resolution(&bmp).unwrap(), (300.0, 300.0))); diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index 7374e26e2b..8c7973e15a 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -28,15 +28,48 @@ fn open(s: &mut Session, name: &str, bytes: &[u8]) -> Value { } /// A `w`×`h` image of one colour in `format`. -fn image_bytes(w: u32, h: u32, format: image::ImageFormat) -> Vec { +fn image_bytes(w: u32, h: u32, format: craft_image_codecs::Format) -> Vec { let rgba = image::RgbaImage::from_pixel(w, h, image::Rgba([200, 30, 40, 255])); - let img = if format == image::ImageFormat::Jpeg { + let img = if format == craft_image_codecs::Format::Jpeg { image::DynamicImage::ImageRgb8(image::DynamicImage::ImageRgba8(rgba).to_rgb8()) } else { rgba.into() }; let mut out = Vec::new(); - img.write_to(&mut Cursor::new(&mut out), format).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, format, &craft_image_codecs::EncodeOptions::default()).map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); out } @@ -84,12 +117,12 @@ fn opens_every_readable_format() { assert!(s.doc().unwrap().doc.node_count() >= 2, "{name}: the rectangle came through"); } for (name, kind) in [ - ("p.png", image::ImageFormat::Png), - ("p.jpg", image::ImageFormat::Jpeg), - ("p.gif", image::ImageFormat::Gif), - ("p.webp", image::ImageFormat::WebP), - ("p.tif", image::ImageFormat::Tiff), - ("p.bmp", image::ImageFormat::Bmp), + ("p.png", craft_image_codecs::Format::Png), + ("p.jpg", craft_image_codecs::Format::Jpeg), + ("p.gif", craft_image_codecs::Format::Gif), + ("p.webp", craft_image_codecs::Format::WebP), + ("p.tif", craft_image_codecs::Format::Tiff), + ("p.bmp", craft_image_codecs::Format::Bmp), ] { let r = open(&mut s, name, &image_bytes(5, 4, kind)); assert_eq!(r["format"], format(name.rsplit('.').next().unwrap()).unwrap().id, "{name}"); @@ -107,12 +140,12 @@ fn opens_every_readable_format() { #[test] fn webp_opens_at_its_pixel_size() { let mut s = Session::new(); - open(&mut s, "tiny.webp", &image_bytes(3, 2, image::ImageFormat::WebP)); + open(&mut s, "tiny.webp", &image_bytes(3, 2, craft_image_codecs::Format::WebP)); let im = image_of(&s); assert_eq!((im.width, im.height), (3, 2)); let ab = s.doc().unwrap().doc.artboards[0].rect; assert_eq!((ab.width(), ab.height()), (3.0, 2.0)); - let r = raster_image(&image_bytes(3, 2, image::ImageFormat::WebP)).unwrap(); + let r = raster_image(&image_bytes(3, 2, craft_image_codecs::Format::WebP)).unwrap(); assert_eq!((r.width, r.height, r.blob.mime.as_str()), (3, 2, "image/webp")); } @@ -123,7 +156,7 @@ fn cmyk_tiffs_keep_their_inks_and_other_tiffs_become_png() { let r = raster_image(&tiff.bytes).unwrap(); assert_eq!((r.width, r.height, r.blob.mime.as_str()), (2, 1, "image/tiff")); assert_eq!(r.blob.cmyk(), Some(inks)); - let rgb = raster_image(&image_bytes(2, 1, image::ImageFormat::Tiff)).unwrap(); + let rgb = raster_image(&image_bytes(2, 1, craft_image_codecs::Format::Tiff)).unwrap(); assert_eq!(rgb.blob.mime, "image/png"); } @@ -140,7 +173,25 @@ fn kept(what: &str, bytes: &[u8]) -> (Option>, Vec) { let r = raster_image(bytes).unwrap_or_else(|e| panic!("{what}: {e}")); assert_eq!((r.width, r.height, r.ppi), (3, 2, Some((150.0, 150.0))), "{what}"); assert_eq!(super::ppi::resolution(&r.blob.bytes), Some((150.0, 150.0)), "{what}: the stored image keeps the resolution"); - let rgba = image::load_from_memory(&r.blob.bytes).unwrap_or_else(|e| panic!("{what}: {e}")).to_rgba8().into_raw(); + let rgba = craft_image_codecs::decode(&r.blob.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap_or_else(|e| panic!("{what}: {e}")) + .to_rgba8() + .into_raw(); (r.blob.cmyk().map(|i| i.data), rgba) } @@ -241,7 +292,26 @@ fn planar_cmyk_tiffs_open_and_place_with_their_inks() { let inks = [vec![255u16, 0, 12, 0, 40, 9], vec![0, 255, 34, 0, 50, 8], vec![0, 0, 56, 0, 60, 7], vec![0, 0, 78, 255, 70, 6]]; let file = hand_tiff(5, 8, &[], true, &inks); let want: Vec = (0..6).flat_map(|i| inks.iter().map(move |v| v[i] as u8)).collect(); - assert!(image::load_from_memory(&file).is_err(), "the image decoder reads planar CMYK now"); + assert!( + craft_image_codecs::decode(&file) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .is_err(), + "the image decoder reads planar CMYK now" + ); let mut s = Session::new(); open(&mut s, "planar.tif", &file); let blob = &s.doc().unwrap().doc.images[&image_of(&s).key]; @@ -250,7 +320,26 @@ fn planar_cmyk_tiffs_open_and_place_with_their_inks() { s.execute("file.place", &json!({"name": "planar.tif", "dataBase64": vectorcraft_format::base64_encode(&file)})).unwrap(); let blob = &s.doc().unwrap().doc.images[&image_of(&s).key]; assert_eq!(blob.cmyk().map(|i| i.data), Some(want), "Place keeps the inks"); - assert!(image::load_from_memory(&blob.bytes).is_ok(), "the image decoder reads the stored image"); + assert!( + craft_image_codecs::decode(&blob.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .is_ok(), + "the image decoder reads the stored image" + ); } /// A 70 × 7 picture, `true` for black: a white row and a black row (runs past 63 take a make-up @@ -295,12 +384,49 @@ fn ccitt_group3_tiffs_open_and_place_with_their_pixels() { rtc, }; let file = vectorcraft_testkit::tiff::group3(&g); - assert!(image::load_from_memory(&file).is_err(), "{what}: the image decoder reads Group 3 now"); + assert!( + craft_image_codecs::decode(&file) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .is_err(), + "{what}: the image decoder reads Group 3 now" + ); // A black run's pixels are 1 bits, which show as black when white is zero. let want: Vec = rows.concat().iter().map(|&black| if black == (photometric == 0) { 0 } else { 255 }).collect(); let pixels = |s: &Session| { let blob = &s.doc().unwrap().doc.images[&image_of(s).key]; - image::load_from_memory(&blob.bytes).unwrap_or_else(|e| panic!("{what}: {e}")).to_luma8().into_raw() + craft_image_codecs::decode(&blob.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap_or_else(|e| panic!("{what}: {e}")) + .to_luma8() + .into_raw() }; open(&mut s, "fax.tif", &file); assert_eq!(pixels(&s), want, "{what}: Open"); @@ -362,7 +488,7 @@ fn ccitt_group3_tiffs_too_large_or_cut_short_are_refused() { #[test] fn content_beats_a_wrong_extension() { - let png = image_bytes(2, 2, image::ImageFormat::Png); + let png = image_bytes(2, 2, craft_image_codecs::Format::Png); assert_eq!(detect("photo.jpg", &png).unwrap().id, "png"); assert_eq!(detect("noext", b"").unwrap().id, "svg"); assert_eq!(detect("x.ait", b"%PDF-1.7").unwrap().id, "ait"); @@ -570,7 +696,27 @@ fn pdf_export_honours_artboard_and_range() { // Single-image formats take one artboard. assert!(s.execute("document.export", &json!({"format": "png", "range": "1-2"})).is_err()); let png = b64(&s.execute("document.export", &json!({"format": "png", "range": "2", "scale": 0.5})).unwrap()); - assert_eq!(image::load_from_memory(&png).unwrap().width(), 50); + assert_eq!( + craft_image_codecs::decode(&png) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .width(), + 50 + ); assert!(s.execute("document.export", &json!({"format": "png", "scale": "big"})).is_err(), "typed options reject a bad type"); } @@ -611,7 +757,26 @@ fn template_doc() -> (Session, u64, u64) { } fn has_red(png: &[u8]) -> bool { - image::load_from_memory(png).unwrap().to_rgba8().pixels().any(|p| p[0] > 200 && p[2] < 80 && p[3] > 0) + craft_image_codecs::decode(png) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() + .pixels() + .any(|p| p[0] > 200 && p[2] < 80 && p[3] > 0) } #[test] @@ -619,7 +784,29 @@ fn raster_exports_leave_template_layers_out() { let (mut s, red, blue) = template_doc(); let png = b64(&s.execute("document.export", &json!({"format": "png"})).unwrap()); assert!(!has_red(&png), "no red pixels from the template layer"); - assert!(image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(75, 50)[2] > 200, "the normal layer is exported"); + assert!( + craft_image_codecs::decode(&png) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() + .get_pixel(75, 50)[2] + > 200, + "the normal layer is exported" + ); s.execute("select.set", &json!({"ids": [red, blue]})).unwrap(); let r = s.execute("document.exportSelection", &json!({"format": "png"})).unwrap(); assert!(!has_red(&b64(&r))); @@ -651,7 +838,27 @@ fn export_for_screens_one_page_per_pdf_unique_names() { // No folder: the files come back as bytes. let r = s.execute("document.exportForScreens", &json!({"range": "3", "formats": [{"format": "jpg", "scale": 0.5}]})).unwrap(); assert_eq!(r["files"][0]["name"], "Artboard-3@0.5x.jpg"); - assert_eq!(image::load_from_memory(&b64(&r["files"][0])).unwrap().width(), 50); + assert_eq!( + craft_image_codecs::decode(&b64(&r["files"][0])) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .width(), + 50 + ); // A native row: each artboard as a document of its own to edit. let r = s.execute("document.exportForScreens", &json!({"range": "1", "formats": [{"format": "vectorcraft"}]})).unwrap(); assert!(r["files"][0]["name"].as_str().unwrap().ends_with(".vectorcraft"), "{r}"); @@ -921,7 +1128,41 @@ fn a_photo_places_the_way_its_exif_orientation_says() { } } let mut jpg = Vec::new(); - image::DynamicImage::ImageRgb8(rgb).write_to(&mut Cursor::new(&mut jpg), image::ImageFormat::Jpeg).unwrap(); + { + let __dyn: image::DynamicImage = (image::DynamicImage::ImageRgb8(rgb)).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Jpeg, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| jpg.extend_from_slice(&__b)) + } + .unwrap(); // An EXIF segment with Orientation 6: turn a quarter clockwise to show. let exif: Vec = [b"Exif\0\0".as_slice(), b"II", &[0x2a, 0, 8, 0, 0, 0], &[1, 0], &[0x12, 0x01, 3, 0, 1, 0, 0, 0, 6, 0, 0, 0], &[0, 0, 0, 0]].concat(); @@ -934,7 +1175,24 @@ fn a_photo_places_the_way_its_exif_orientation_says() { assert_eq!((plain.width, plain.height, plain.blob.bytes.as_slice()), (16, 8, jpg.as_slice()), "a photo as taken keeps its bytes"); let img = raster_image(&turned).unwrap(); assert_eq!((img.width, img.height), (8, 16), "turned a quarter"); - let px = image::load_from_memory(&img.blob.bytes).unwrap().to_rgb8(); + let px = craft_image_codecs::decode(&img.blob.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgb8(); let red = |p: &image::Rgb| p[0] > 150 && p[1] < 80; assert!(red(px.get_pixel(4, 3)) && !red(px.get_pixel(4, 12)), "the left half is on top"); } @@ -980,7 +1238,41 @@ fn a_quarter_turn_swaps_the_resolution_axes() { // 48 × 32: the top-left 16 × 16 (one whole JPEG MCU) red, the rest white. let rgb = image::RgbImage::from_fn(48, 32, |x, y| if x < 16 && y < 16 { image::Rgb([220, 0, 0]) } else { image::Rgb([255, 255, 255]) }); let mut jpg = Vec::new(); - image::DynamicImage::ImageRgb8(rgb).write_to(&mut Cursor::new(&mut jpg), image::ImageFormat::Jpeg).unwrap(); + { + let __dyn: image::DynamicImage = (image::DynamicImage::ImageRgb8(rgb)).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Jpeg, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| jpg.extend_from_slice(&__b)) + } + .unwrap(); for orientation in [0u16, 1, 2, 3, 4, 5, 6, 7, 8, 9] { let exif = [b"Exif\0\0".as_slice(), &exif_block(orientation, (300, 150))].concat(); // Without a JFIF density the resolution comes from the EXIF block. @@ -996,7 +1288,24 @@ fn a_quarter_turn_swaps_the_resolution_axes() { let img = raster_image(&turned).unwrap(); assert_eq!(((img.width, img.height), img.ppi), (size, Some(ppi)), "{what}"); assert_eq!(super::ppi::resolution(&img.blob.bytes), Some(ppi), "{what}: the stored image"); - let px = image::load_from_memory(&img.blob.bytes).unwrap().to_rgb8(); + let px = craft_image_codecs::decode(&img.blob.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgb8(); let red = |x: u32, y: u32| px.get_pixel(x, y)[1] < 80; let (w, h) = size; let corners = [(false, false), (true, false), (true, true), (false, true)]; @@ -1058,7 +1367,26 @@ fn tiffs_read_without_the_image_decoder_follow_their_orientation() { let fax = vectorcraft_testkit::tiff::group3(&g); // The Group 3 file declares no resolution. for (kind, file, y_ppi) in [("Group 3", fax, None), ("gray with alpha", gray, Some(300))] { - assert!(image::load_from_memory(&file).is_err(), "{kind}: the image decoder reads it now"); + assert!( + craft_image_codecs::decode(&file) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .is_err(), + "{kind}: the image decoder reads it now" + ); for (orientation, long) in (1..=8).flat_map(|o| [(o, false), (o, true)]) { let what = format!("{kind}, orientation {orientation}, LONG {long}"); let img = raster_image(&tiff_oriented(&file, orientation, long, y_ppi)).unwrap_or_else(|e| panic!("{what}: {e}")); @@ -1067,7 +1395,24 @@ fn tiffs_read_without_the_image_decoder_follow_their_orientation() { let ppi = y_ppi.map(|y| if quarter { (f64::from(y), 150.0) } else { (150.0, f64::from(y)) }); assert_eq!(((img.width, img.height), img.ppi), (size, ppi), "{what}"); assert_eq!(super::ppi::resolution(&img.blob.bytes), ppi, "{what}: the stored image"); - let px = image::load_from_memory(&img.blob.bytes).unwrap().to_luma8(); + let px = craft_image_codecs::decode(&img.blob.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_luma8(); let (right, bottom) = first_pixel_at(orientation); let (x, y) = (if right { size.0 - 1 } else { 0 }, if bottom { size.1 - 1 } else { 0 }); let black: Vec<_> = px.enumerate_pixels().filter(|p| p.2[0] < 128).map(|p| (p.0, p.1)).collect(); @@ -1156,18 +1501,25 @@ fn cmyk_jpegs_turned_by_their_orientation_keep_their_inks() { /// half turn keeps them. #[test] fn png_webp_and_rgb_tiff_turned_a_quarter_swap_their_resolution() { - use image::ImageEncoder as _; let rgb = image::RgbImage::from_fn(3, 2, |x, y| image::Rgb(if x == 0 && y == 0 { [0, 0, 0] } else { [255, 255, 255] })); for orientation in [3u16, 6, 8] { - let mut png = Vec::new(); - let mut enc = image::codecs::png::PngEncoder::new(&mut png); - enc.set_exif_metadata(exif_block(orientation, (150, 300))).unwrap(); - enc.write_image(rgb.as_raw(), 3, 2, image::ExtendedColorType::Rgb8).unwrap(); + let mut cimg = craft_image_codecs::Image::from_raw( + 3, + 2, + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U8, + rgb.as_raw().to_vec(), + ) + .unwrap(); + cimg.meta.exif = Some(exif_block(orientation, (150, 300))); + let png = craft_image_codecs::encode(&cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); let png = super::ppi::with_png_resolution(&png, (150.0, 300.0)); - let mut webp = Vec::new(); - let mut enc = image::codecs::webp::WebPEncoder::new_lossless(&mut webp); - enc.set_exif_metadata(exif_block(orientation, (150, 300))).unwrap(); - enc.write_image(rgb.as_raw(), 3, 2, image::ExtendedColorType::Rgb8).unwrap(); + let webp = craft_image_codecs::encode( + &cimg, + craft_image_codecs::Format::WebP, + &craft_image_codecs::EncodeOptions { webp_lossless: true, ..craft_image_codecs::EncodeOptions::default() }, + ) + .unwrap(); let channel = |c: usize| -> Vec { rgb.pixels().map(|p| u16::from(p[c])).collect() }; let tiff = tiff_oriented(&hand_tiff(2, 8, &[], false, &[channel(0), channel(1), channel(2)]), orientation, false, Some(300)); for (kind, file) in [("PNG", png), ("WebP", webp), ("TIFF", tiff)] { @@ -1178,7 +1530,24 @@ fn png_webp_and_rgb_tiff_turned_a_quarter_swap_their_resolution() { let img = raster_image(&file).unwrap_or_else(|e| panic!("{what}: {e}")); assert_eq!(((img.width, img.height), img.ppi), (size, Some(ppi)), "{what}"); assert_eq!(super::ppi::resolution(&img.blob.bytes), Some(ppi), "{what}: the stored image"); - let px = image::load_from_memory(&img.blob.bytes).unwrap().to_luma8(); + let px = craft_image_codecs::decode(&img.blob.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_luma8(); let (right, bottom) = first_pixel_at(orientation); let at = (if right { size.0 - 1 } else { 0 }, if bottom { size.1 - 1 } else { 0 }); let black: Vec<_> = px.enumerate_pixels().filter(|p| p.2[0] < 128).map(|p| (p.0, p.1)).collect(); @@ -1225,18 +1594,34 @@ fn tiff_with_icc(tiff: &[u8], icc: &[u8]) -> Vec { out } -/// The ICC profile and pixels of a stored image, read by the image decoder for its format. -fn stored_pixels(what: &str, img: &RasterImage) -> (Option>, image::ExtendedColorType, image::DynamicImage) { - use image::ImageDecoder as _; - let bytes = Cursor::new(img.blob.bytes.as_slice()); - let mut d: Box = match img.blob.mime.as_str() { - "image/png" => Box::new(image::codecs::png::PngDecoder::new(bytes).unwrap()), - "image/tiff" => Box::new(image::codecs::tiff::TiffDecoder::new(bytes).unwrap()), +/// The ICC profile, sample bit depth, and pixels of a stored image, read by the image decoder for its format. +fn stored_pixels(what: &str, img: &RasterImage) -> (Option>, u16, image::DynamicImage) { + let fmt = match img.blob.mime.as_str() { + "image/png" => craft_image_codecs::Format::Png, + "image/tiff" => craft_image_codecs::Format::Tiff, other => panic!("{what}: stored as {other}"), }; - let icc = d.icc_profile().unwrap(); - let color = d.original_color_type(); - (icc, color, image::DynamicImage::from_decoder(d).unwrap()) + let opts = craft_image_codecs::DecodeOptions { keep_orientation: true, ..Default::default() }; + let decoded = craft_image_codecs::decode_as_with(fmt, img.blob.bytes.as_slice(), &opts).unwrap(); + let icc = decoded.meta.icc.clone(); + let bits = u16::try_from(decoded.sample_type().bytes() * 8).unwrap(); + let (w, h) = decoded.dimensions(); + let dyn_img = match (decoded.layout(), decoded.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(w, h, decoded.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U16) => { + image::DynamicImage::ImageLuma16(image::ImageBuffer::from_raw(w, h, decoded.to_u16_samples().unwrap()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(w, h, decoded.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U16) => { + image::DynamicImage::ImageRgb16(image::ImageBuffer::from_raw(w, h, decoded.to_u16_samples().unwrap()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(w, h, decoded.to_rgba8()).unwrap()), + }; + (icc, bits, dyn_img) } /// An image turned by its orientation and stored as PNG keeps the gray or RGB ICC profile its file @@ -1245,7 +1630,7 @@ fn stored_pixels(what: &str, img: &RasterImage) -> (Option>, image::Exte /// space than the samples' is left out. #[test] fn images_stored_as_png_keep_their_icc_profile_and_16_bit_samples() { - use image::{DynamicImage, ImageEncoder as _}; + use image::DynamicImage; let (rgb_icc, gray_icc, cmyk_icc) = (icc_profile(b"RGB ", 600), icc_profile(b"GRAY", 300), icc_profile(b"CMYK", 400)); // 3 × 2, every sample's low byte different. let rgb16 = image::ImageBuffer::from_fn(3, 2, |x, y| { @@ -1255,27 +1640,56 @@ fn images_stored_as_png_keep_their_icc_profile_and_16_bit_samples() { let rgb16 = DynamicImage::ImageRgb16(rgb16); let gray16 = DynamicImage::ImageLuma16(image::ImageBuffer::from_fn(3, 2, |x, y| image::Luma([u16::try_from(x * 0x3001 + y * 0x0107).unwrap()]))); let rgb8 = DynamicImage::ImageRgb8(image::RgbImage::from_fn(3, 2, |x, y| image::Rgb([u8::try_from(x * 70 + y * 9).unwrap(), 200, 13]))); + let to_cimg = |img: &DynamicImage| -> craft_image_codecs::Image { + match img { + DynamicImage::ImageRgb8(b) => craft_image_codecs::Image::from_raw( + b.width(), + b.height(), + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U8, + b.as_raw().to_vec(), + ) + .unwrap(), + DynamicImage::ImageRgb16(b) => craft_image_codecs::Image::from_raw( + b.width(), + b.height(), + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.as_raw().iter().flat_map(|s| s.to_ne_bytes()).collect(), + ) + .unwrap(), + DynamicImage::ImageLuma16(b) => craft_image_codecs::Image::from_raw( + b.width(), + b.height(), + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.as_raw().iter().flat_map(|s| s.to_ne_bytes()).collect(), + ) + .unwrap(), + _ => unreachable!(), + } + }; let png = |img: &DynamicImage, icc: &[u8], orientation: u16| { - let mut out = Vec::new(); - let mut enc = image::codecs::png::PngEncoder::new(&mut out); - enc.set_icc_profile(icc.to_vec()).unwrap(); - enc.set_exif_metadata(exif_block(orientation, (150, 150))).unwrap(); - img.write_with_encoder(enc).unwrap(); - out + let mut cimg = to_cimg(img); + cimg.meta.icc = Some(icc.to_vec()); + cimg.meta.exif = Some(exif_block(orientation, (150, 150))); + craft_image_codecs::encode(&cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap() }; let webp = { - let mut out = Vec::new(); - let mut enc = image::codecs::webp::WebPEncoder::new_lossless(&mut out); - enc.set_icc_profile(rgb_icc.clone()).unwrap(); - enc.set_exif_metadata(exif_block(6, (150, 150))).unwrap(); - rgb8.write_with_encoder(enc).unwrap(); - out + let mut cimg = to_cimg(&rgb8); + cimg.meta.icc = Some(rgb_icc.clone()); + cimg.meta.exif = Some(exif_block(6, (150, 150))); + craft_image_codecs::encode( + &cimg, + craft_image_codecs::Format::WebP, + &craft_image_codecs::EncodeOptions { webp_lossless: true, ..craft_image_codecs::EncodeOptions::default() }, + ) + .unwrap() }; let tiff = |orientation: Option| { - let mut out = Vec::new(); - let mut enc = image::codecs::tiff::TiffEncoder::new(Cursor::new(&mut out)); - enc.set_icc_profile(rgb_icc.clone()).unwrap(); - rgb16.write_with_encoder(enc).unwrap(); + let mut cimg = to_cimg(&rgb16); + cimg.meta.icc = Some(rgb_icc.clone()); + let out = craft_image_codecs::encode(&cimg, craft_image_codecs::Format::Tiff, &craft_image_codecs::EncodeOptions::default()).unwrap(); match orientation { Some(o) => tiff_oriented(&out, o, false, None), None => out, @@ -1295,9 +1709,9 @@ fn images_stored_as_png_keep_their_icc_profile_and_16_bit_samples() { for (what, file, icc, want, wide) in cases { let img = raster_image(&file).unwrap_or_else(|e| panic!("{what}: {e}")); assert_eq!((img.width, img.height, img.blob.mime.as_str()), (want.width(), want.height(), "image/png"), "{what}"); - let (kept, color, px) = stored_pixels(what, &img); + let (kept, bits, px) = stored_pixels(what, &img); assert_eq!(kept.as_deref(), icc, "{what}: the ICC profile"); - assert_eq!(color.bits_per_pixel() / u16::from(color.channel_count()), if wide { 16 } else { 8 }, "{what}: the sample depth"); + assert_eq!(bits, if wide { 16 } else { 8 }, "{what}: the sample depth"); if wide { assert_eq!(px.to_rgb16(), want.to_rgb16(), "{what}: the samples"); } else { @@ -1305,10 +1719,14 @@ fn images_stored_as_png_keep_their_icc_profile_and_16_bit_samples() { } } // A JPEG's samples change in encoding; its profile is kept. - let mut jpg = Vec::new(); - let mut enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpg, 95); - enc.set_icc_profile(rgb_icc.clone()).unwrap(); - rgb8.write_with_encoder(enc).unwrap(); + let mut cimg = to_cimg(&rgb8); + cimg.meta.icc = Some(rgb_icc.clone()); + let jpg = craft_image_codecs::encode( + &cimg, + craft_image_codecs::Format::Jpeg, + &craft_image_codecs::EncodeOptions { jpeg_quality: 95, ..craft_image_codecs::EncodeOptions::default() }, + ) + .unwrap(); let exif = [b"Exif\0\0".as_slice(), &exif_block(6, (150, 150))].concat(); let mut turned = jpg[..2].to_vec(); turned.extend([0xff, 0xe1]); @@ -1444,7 +1862,23 @@ fn export_for_screens_jpgs_open_in_every_colour_model() { assert_eq!(bytes.get(..2), Some(&[0xFF, 0xD8][..]), "{what}: starts with SOI"); let jfif = bytes.get(2..4) == Some(&[0xFF, 0xE0][..]); assert_eq!(jfif, components != 4, "{what}: JFIF only on one- and three-component files"); - let image = image::load_from_memory(&bytes).unwrap_or_else(|e| panic!("{what}: {e}")); + let image = craft_image_codecs::decode(&bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap_or_else(|e| panic!("{what}: {e}")); assert_eq!(image.width(), width, "{what}"); } } diff --git a/crates/engine/src/cmd/fileio/tests_affinity.rs b/crates/engine/src/cmd/fileio/tests_affinity.rs index d5f5149bab..54fca28217 100644 --- a/crates/engine/src/cmd/fileio/tests_affinity.rs +++ b/crates/engine/src/cmd/fileio/tests_affinity.rs @@ -9,7 +9,41 @@ use std::io::Cursor; fn png() -> Vec { let im = image::RgbaImage::from_fn(2, 1, |x, _| if x == 0 { image::Rgba([220, 40, 60, 255]) } else { image::Rgba([0, 0, 0, 0]) }); let mut bytes = Vec::new(); - im.write_to(&mut Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (im).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| bytes.extend_from_slice(&__b)) + } + .unwrap(); bytes } diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index c48b437b76..533b397b42 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -571,7 +571,24 @@ fn a_one_bit_rgb_image_opens_from_the_editing_data_in_its_colors() { assert_eq!(names(&doc.layers), ["Art"], "{r}"); let mut found = vec![]; doc.visit_images(|_, im| { - let img = image::load_from_memory(&doc.images[&im.key].bytes).unwrap().to_rgb8(); + let img = craft_image_codecs::decode(&doc.images[&im.key].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgb8(); found.push(img.pixels().map(|p| p.0).collect::>()); }); assert_eq!(found, [[[255, 0, 0], [0, 255, 0], [0, 0, 255]]], "{r}"); @@ -589,7 +606,27 @@ fn a_zero_width_stroke_in_the_editing_data_draws_a_hairline() { assert_eq!(names(&s.doc().unwrap().doc.layers), ["Art"], "{r}"); let v = s.execute("document.export", &json!({"format": "png", "background": "transparent"})).unwrap(); let png = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap(); - image::load_from_memory(&png).unwrap().to_rgba8().pixels().filter(|p| p.0[3] > 0).count() + craft_image_codecs::decode(&png) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() + .pixels() + .filter(|p| p.0[3] > 0) + .count() }; assert!(drawn("0 1 1 0 1 0 0 XA\n0 w\n20 20 m\n180 80 L\nS\n") > 0, "the hairline draws"); assert_eq!(drawn("0 1 1 0 1 0 0 XA\n0 w\n20 20 m\n180 80 L\nN\n"), 0, "the unstroked path draws nothing"); diff --git a/crates/engine/src/cmd/fileio/tests_artboard_fill.rs b/crates/engine/src/cmd/fileio/tests_artboard_fill.rs index 371cdc05ab..a735b72b42 100644 --- a/crates/engine/src/cmd/fileio/tests_artboard_fill.rs +++ b/crates/engine/src/cmd/fileio/tests_artboard_fill.rs @@ -32,7 +32,24 @@ fn with(mut p: Value, more: &Value) -> Value { /// The pixels of the PNG `document.export` writes of the active document with `p`, on transparency. fn png(s: &mut Session, p: Value) -> image::RgbaImage { let v = s.execute("document.export", &with(json!({"format": "png", "background": "transparent"}), &p)).unwrap(); - image::load_from_memory(&b64(&v)).unwrap().to_rgba8() + craft_image_codecs::decode(&b64(&v)) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() } /// The file `document.export` writes with `p`. @@ -61,7 +78,26 @@ fn raster_exports_paint_the_color_behind_the_art() { assert_eq!(png(&mut s, json!({"artboard": 0, "includeArtboardFill": false})).get_pixel(2, 2)[3], 0, "left out"); assert_eq!(png(&mut s, json!({"artboard": 1})).get_pixel(2, 2)[3], 0, "an artboard without a color"); let jpg = file(&mut s, json!({"format": "jpg", "artboard": 0, "quality": 100})); - let px = image::load_from_memory(&jpg).unwrap().to_rgb8().get_pixel(2, 2).0; + let px = craft_image_codecs::decode(&jpg) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgb8() + .get_pixel(2, 2) + .0; assert!(px[0] > 240 && px[1] < 16 && px[2] < 16, "JPEG too: {px:?}"); for bad in [json!("no"), json!(1)] { assert!(s.execute("document.export", &json!({"format": "png", "includeArtboardFill": bad})).is_err(), "{bad}"); @@ -163,7 +199,28 @@ fn export_for_screens_includes_the_fill_unless_unchecked() { let p = with(json!({"artboards": [0], "formats": [{"format": "png"}], "settings": {"png": {"background": "transparent"}}}), &more); s.execute("document.exportForScreens", &p).unwrap() }; - let corner = |r: &Value| image::load_from_memory(&b64(&r["files"][0])).unwrap().to_rgba8().get_pixel(2, 2).0; + let corner = |r: &Value| { + craft_image_codecs::decode(&b64(&r["files"][0])) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() + .get_pixel(2, 2) + .0 + }; assert_eq!(corner(&screens(&mut s, json!({}))), RED, "on by default"); assert_eq!(corner(&screens(&mut s, json!({"includeArtboardFill": false})))[3], 0, "unchecked"); assert_eq!(s.execute("document.exportSettings", &json!({})).unwrap()["settings"]["includeArtboardFill"], false, "remembered"); diff --git a/crates/engine/src/cmd/fileio/tests_eps.rs b/crates/engine/src/cmd/fileio/tests_eps.rs index db667e6ef2..e37fd2be37 100644 --- a/crates/engine/src/cmd/fileio/tests_eps.rs +++ b/crates/engine/src/cmd/fileio/tests_eps.rs @@ -50,7 +50,23 @@ fn eps_covers_the_art_y_up_from_the_first_artboard_with_a_preview_and_the_docume let bytes = b64(&r); // The default TIFF preview sits behind the binary header. let (_, tiff) = vectorcraft_eps::sections(&bytes).unwrap(); - let preview = image::load_from_memory_with_format(tiff.unwrap(), image::ImageFormat::Tiff).unwrap(); + let preview = craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, tiff.unwrap()) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap(); assert_eq!((preview.width(), preview.height()), (100, 40)); let ps = postscript(&bytes); assert_eq!(dsc(&ps, "BoundingBox").as_deref(), Some("50 100 150 140"), "60..100 down is 100..140 up"); @@ -221,13 +237,47 @@ fn placed_images_are_written_and_previews_are_black_and_white_on_request() { /// The PNG thumbnail of an EPS file, decoded. fn thumbnail_png(bytes: &[u8]) -> image::RgbaImage { let png = vectorcraft_eps::thumbnail(bytes).expect("a thumbnail"); - image::load_from_memory_with_format(&png, image::ImageFormat::Png).unwrap().to_rgba8() + craft_image_codecs::decode_as(craft_image_codecs::Format::Png, &png) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() } /// The TIFF preview of an EPS file, decoded. fn preview_tiff(bytes: &[u8]) -> image::RgbaImage { let tiff = vectorcraft_eps::sections(bytes).unwrap().1.expect("a preview"); - image::load_from_memory_with_format(tiff, image::ImageFormat::Tiff).unwrap().to_rgba8() + craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, tiff) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() } /// The size of a thumbnail render of the rect an EPS file's preview shows (its bounding box). diff --git a/crates/engine/src/cmd/fileio/tests_epsimport.rs b/crates/engine/src/cmd/fileio/tests_epsimport.rs index 59caf85d6e..629febc77c 100644 --- a/crates/engine/src/cmd/fileio/tests_epsimport.rs +++ b/crates/engine/src/cmd/fileio/tests_epsimport.rs @@ -115,7 +115,25 @@ fn tiff_predicted_4_bit_images_open_from_eps_and_postscript_ai_files() { let mut grays = vec![]; d.walk(|n| { if let vectorcraft_doc::NodeKind::Image(im) = &n.kind { - grays = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_luma8().into_raw(); + grays = craft_image_codecs::decode(&d.images[&im.key].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_luma8() + .into_raw(); } }); assert_eq!(grays, [0, 5, 15, 3, 9, 9, 2, 0].map(|v| v * 17), "{name}"); diff --git a/crates/engine/src/cmd/fileio/tests_exportas.rs b/crates/engine/src/cmd/fileio/tests_exportas.rs index 1908c39685..49680347b2 100644 --- a/crates/engine/src/cmd/fileio/tests_exportas.rs +++ b/crates/engine/src/cmd/fileio/tests_exportas.rs @@ -16,7 +16,24 @@ fn b64(v: &Value) -> Vec { } fn rgba(bytes: &[u8]) -> image::RgbaImage { - image::load_from_memory(bytes).unwrap().to_rgba8() + craft_image_codecs::decode(bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() } fn tmp_dir(tag: &str) -> std::path::PathBuf { diff --git a/crates/engine/src/cmd/fileio/tests_heifread.rs b/crates/engine/src/cmd/fileio/tests_heifread.rs index 9820164da5..4b4a11b0c9 100644 --- a/crates/engine/src/cmd/fileio/tests_heifread.rs +++ b/crates/engine/src/cmd/fileio/tests_heifread.rs @@ -37,7 +37,24 @@ fn centers(side: u32) -> [(u32, u32); 4] { #[cfg(feature = "heif")] fn decoded(bytes: &[u8]) -> image::RgbaImage { let raster = load::raster_image(bytes).unwrap(); - image::load_from_memory(&raster.blob.bytes).unwrap().to_rgba8() + craft_image_codecs::decode(&raster.blob.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() } #[cfg(feature = "heif")] @@ -65,7 +82,28 @@ fn quadrants_open_and_place_as_their_pixels() { assert_eq!(opened["format"], "heif", "{name}"); assert_eq!(s.doc().unwrap().doc.artboards[0].rect.size(), vectorcraft_geom::Size::new(32.0, 32.0)); let blob = s.doc().unwrap().doc.images.values().next().unwrap(); - assert_quadrants(&image::load_from_memory(&blob.bytes).unwrap().to_rgba8(), 32, name); + assert_quadrants( + &craft_image_codecs::decode(&blob.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(), + 32, + name, + ); s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); let placed = s.execute("file.place", &json!({"name": name, "dataBase64": encoded})).unwrap(); assert_eq!(placed["format"], "heif", "{name}"); @@ -346,8 +384,8 @@ fn damaged_unsupported_and_oversized_files_are_refused() { small[at + 4..at + 8].copy_from_slice(&32u32.to_be_bytes()); let refused = super::heifread::decode(&small, 64 * 64 * 17 - 1).map(|img| img.dimensions()); assert!(refused.as_ref().is_err_and(|e| e.contains("too large to draw")), "{refused:?}"); - // A 128 × 128 grid of four 64 × 64 tiles adds its composed frame, 128 × 128 × 6. - let grid = 128 * 128 * (8 + 6) + 4 * 64 * 64 * 9; + // A 128 × 128 grid of four 64 × 64 tiles. + let grid = 128 * 128 * 17; assert!(super::heifread::decode(GRID, grid).is_ok()); assert!(super::heifread::decode(GRID, grid - 1).unwrap_err().contains("too large to draw")); // The grid's ispe (property 1) claims 16 × 16 pixels; its grid data still composes 128 × 128, @@ -359,255 +397,6 @@ fn damaged_unsupported_and_oversized_files_are_refused() { assert!(super::heifread::decode(&understated, grid - 1).unwrap_err().contains("too large to draw")); } -/// Appends `value` as `n` bits, most significant first. -#[cfg(feature = "heif")] -fn put(bits: &mut Vec, value: u64, n: u32) { - bits.extend((0..n).rev().map(|i| i < 64 && value >> i & 1 == 1)); -} - -/// Appends `value` as an unsigned Exp-Golomb code. -#[cfg(feature = "heif")] -fn put_ue(bits: &mut Vec, value: u64) { - let len = 64 - (value + 1).leading_zeros(); - put(bits, 0, len - 1); - put(bits, value + 1, len); -} - -/// The fields of SPS 0 of `width` × `height` 4:2:0 samples with `sub_layers` sub-layers, each -/// with its profile and level, up to its height. -#[cfg(feature = "heif")] -fn sps_head(width: u64, height: u64, sub_layers: u64) -> Vec { - sps_head_with_id(width, height, sub_layers, 0) -} - -/// [`sps_head`] for SPS `id`. -#[cfg(feature = "heif")] -fn sps_head_with_id(width: u64, height: u64, sub_layers: u64, id: u64) -> Vec { - let mut bits = Vec::new(); - put(&mut bits, 0, 4); - put(&mut bits, sub_layers, 3); - put(&mut bits, 1, 1); - put(&mut bits, 0, 96); - for _ in 0..sub_layers { - put(&mut bits, 0b11, 2); - } - if sub_layers > 0 { - put(&mut bits, 0, 2 * (8 - sub_layers as u32)); - } - for _ in 0..sub_layers { - put(&mut bits, 0, 88 + 8); - } - put_ue(&mut bits, id); - put_ue(&mut bits, 1); - put_ue(&mut bits, width); - put_ue(&mut bits, height); - bits -} - -/// An SPS NAL unit of `bits` (see [`nal`]). -#[cfg(feature = "heif")] -fn sps_nal(bits: Vec) -> Vec { - nal(33, bits) -} - -/// A NAL unit of type `kind` holding `bits`, with its stop bit, and emulation prevention bytes -/// inserted as a stream carries them. -#[cfg(feature = "heif")] -fn nal(kind: u8, mut bits: Vec) -> Vec { - put(&mut bits, 1, 1); - while !bits.len().is_multiple_of(8) { - bits.push(false); - } - let rbsp: Vec = bits.chunks(8).map(|b| b.iter().fold(0u8, |v, &bit| v << 1 | u8::from(bit))).collect(); - let mut nal = vec![kind << 1, 1]; - let mut zeros = 0; - for b in rbsp { - if zeros >= 2 && b <= 3 { - nal.push(3); - zeros = 0; - } - zeros = if b == 0 { zeros + 1 } else { 0 }; - nal.push(b); - } - nal -} - -#[cfg(feature = "heif")] -fn sps(width: u64, height: u64, sub_layers: u64) -> Vec { - sps_nal(sps_head(width, height, sub_layers)) -} - -/// A 64 × 64 SPS that uses every optional part before the VUI's video signal type: a conformance -/// window, sub-layer ordering for two sub-layers, explicit scaling lists, PCM, a reference picture -/// set predicted from another and a long-term picture, then an Extended_SAR aspect ratio and -/// overscan information. `signal` is the full-range flag and the color description, if any. -#[cfg(feature = "heif")] -fn sps_with_vui(signal: Option<(u64, Option<[u64; 3]>)>) -> Vec { - sps_with_vui_and_id(signal, 0) -} - -/// [`sps_with_vui`] for SPS `id`. -#[cfg(feature = "heif")] -fn sps_with_vui_and_id(signal: Option<(u64, Option<[u64; 3]>)>, id: u64) -> Vec { - let mut bits = sps_head_with_id(64, 64, 1, id); - put(&mut bits, 1, 1); - for offset in [0, 2, 0, 2] { - put_ue(&mut bits, offset); - } - put_ue(&mut bits, 0); - put_ue(&mut bits, 0); - // 8 bits of picture order count. - put_ue(&mut bits, 4); - put(&mut bits, 1, 1); - for _ in 0..2 * 3 { - put_ue(&mut bits, 1); - } - for value in [0, 3, 0, 3, 1, 1] { - put_ue(&mut bits, value); - } - // Scaling lists: matrix 1 of each size given explicitly, the others copied. - put(&mut bits, 0b11, 2); - for size in 0..4 { - for matrix in 0..if size == 3 { 2 } else { 6 } { - if matrix == 1 { - put(&mut bits, 1, 1); - if size > 1 { - put_ue(&mut bits, 5); - } - for _ in 0..if size == 0 { 16 } else { 64 } { - put_ue(&mut bits, 3); - } - } else { - put(&mut bits, 0, 1); - put_ue(&mut bits, 0); - } - } - } - // AMP off, SAO on, PCM with its depths, block sizes and loop filter flag. - put(&mut bits, 0b01, 2); - put(&mut bits, 1, 1); - put(&mut bits, 0x77, 8); - put_ue(&mut bits, 0); - put_ue(&mut bits, 1); - put(&mut bits, 0, 1); - // Two short-term sets: one negative and one positive picture, then a set predicted from it - // with three entries (unused with use_delta_flag, used, unused). - put_ue(&mut bits, 2); - put_ue(&mut bits, 1); - put_ue(&mut bits, 1); - for _ in 0..2 { - put_ue(&mut bits, 0); - put(&mut bits, 1, 1); - } - put(&mut bits, 1, 1); - put(&mut bits, 0, 1); - put_ue(&mut bits, 0); - put(&mut bits, 0b01100, 5); - // One long-term picture: 8 bits of picture order count and its used flag. - put(&mut bits, 1, 1); - put_ue(&mut bits, 1); - put(&mut bits, 0xab, 8); - put(&mut bits, 1, 1); - put(&mut bits, 0b11, 2); - // VUI: Extended_SAR 1:1 and overscan information. - put(&mut bits, 1, 1); - put(&mut bits, 1, 1); - put(&mut bits, 255, 8); - put(&mut bits, 0x0001_0001, 32); - put(&mut bits, 1, 1); - put(&mut bits, 0, 1); - match signal { - Some((full, description)) => { - put(&mut bits, 1, 1); - put(&mut bits, 5, 3); - put(&mut bits, full, 1); - put(&mut bits, u64::from(description.is_some()), 1); - for code in description.into_iter().flatten() { - put(&mut bits, code, 8); - } - } - None => put(&mut bits, 0, 1), - } - // No chroma location, field or display window information, timing or restrictions. - put(&mut bits, 0, 8); - sps_nal(bits) -} - -#[cfg(feature = "heif")] -#[test] -fn picture_sizes_come_from_the_sequence_parameter_sets() { - use super::heifread::{picture_bytes, sps_size}; - for sub_layers in [0, 1, 6] { - for (w, h) in [(32, 32), (4032, 3024), (65535, 65535)] { - let nal = sps(w, h, sub_layers); - assert!(nal.windows(3).any(|w| w == [0, 0, 3]), "the profile's zeros need emulation prevention"); - assert_eq!(sps_size(&nal), Some((w, h, 1)), "{w} × {h}, {sub_layers} sub-layers"); - } - } - let mut vps = sps(32, 32, 0); - vps[0] = 32 << 1; - assert_eq!(sps_size(&vps), None); - assert_eq!(sps_size(&sps(32, 32, 0)[..8]), None); - // 4:2:0 is 3 bytes a sample position in each of three sets of planes, in 64-sample blocks. - assert_eq!(picture_bytes(QUADRANTS), Some(64 * 64 * 9)); - assert_eq!(picture_bytes(GRID), Some(4 * 64 * 64 * 9)); - assert!(picture_bytes(ALPHA).unwrap() > 64 * 64 * 9, "the alpha image is counted"); -} - -#[cfg(feature = "heif")] -#[test] -fn the_color_description_comes_from_the_streams_video_signal_type() { - use super::heifread::{sps_signal, sps_size}; - use heic_rs::{MatrixCoefficients, Range}; - let signal = |nal: &[u8]| sps_signal(nal).map(|n| (n.primaries, n.transfer, n.matrix, n.matrix_code, n.range)); - let described = sps_with_vui(Some((1, Some([12, 13, 6])))); - assert_eq!(sps_size(&described), Some((64, 64, 1))); - assert_eq!(signal(&described), Some((12, 13, MatrixCoefficients::Bt601, 6, Range::Full))); - assert_eq!(signal(&sps_with_vui(Some((0, None)))), Some((2, 2, MatrixCoefficients::Unspecified, 2, Range::Limited))); - assert_eq!(signal(&sps_with_vui(None)), None); - assert_eq!(signal(&sps(64, 64, 0)), None, "cut short before its VUI"); - // The ICC-only fixture's stream: heif-enc writes full-range BT.601. - let ctx = heic_rs::context::Context::open(TONES_P3_ICC_ONLY).unwrap(); - let props = ctx.props(ctx.meta.primary).unwrap(); - assert!(props.nclx.is_none() && props.icc.is_some()); - let sets = props.hvcc.unwrap().parameter_sets(); - let nal = sets.into_iter().find(|nal| nal[0] >> 1 & 0x3f == 33).unwrap(); - assert_eq!(sps_signal(nal).map(|n| (n.matrix, n.range)), Some((MatrixCoefficients::Bt601, Range::Full))); -} - -#[cfg(feature = "heif")] -#[test] -fn the_slices_picture_parameter_set_picks_the_sps() { - use super::heifread::{active_sps, sps_signal}; - use heic_rs::Range; - let full = sps_with_vui_and_id(Some((1, Some([1, 13, 6]))), 0); - let limited = sps_with_vui_and_id(Some((0, Some([1, 13, 1]))), 1); - let pps = |id: u64, sps: u64| { - let mut bits = Vec::new(); - put_ue(&mut bits, id); - put_ue(&mut bits, sps); - nal(34, bits) - }; - // first_slice_segment_in_pic_flag, no_output_of_prior_pics_flag for an IDR picture (type 19), - // slice_pic_parameter_set_id. - let slice = |kind: u8, pps: u64| { - let mut bits = vec![true]; - if kind == 19 { - bits.push(false); - } - put_ue(&mut bits, pps); - nal(kind, bits) - }; - let (pps0, pps3) = (pps(0, 0), pps(3, 1)); - let sets = [full.as_slice(), limited.as_slice(), pps0.as_slice(), pps3.as_slice()]; - let (idr3, trail0, idr5) = (slice(19, 3), slice(1, 0), slice(19, 5)); - assert_eq!(active_sps(&sets, &[&idr3]), Some(limited.as_slice())); - assert_eq!(active_sps(&sets, &[&trail0]), Some(full.as_slice())); - assert_eq!(active_sps(&sets, &[&idr5]), None, "no PPS 5"); - assert_eq!(active_sps(&sets, &[&pps0]), None, "no slice"); - assert_eq!(active_sps(&sets, &[&idr3]).and_then(sps_signal).map(|n| (n.matrix_code, n.range)), Some((1, Range::Limited))); -} - #[cfg(not(feature = "heif"))] #[test] fn a_build_without_the_decoder_refuses_heif_files_with_a_message() { diff --git a/crates/engine/src/cmd/fileio/tests_jp2read.rs b/crates/engine/src/cmd/fileio/tests_jp2read.rs index e028350150..6075afd224 100644 --- a/crates/engine/src/cmd/fileio/tests_jp2read.rs +++ b/crates/engine/src/cmd/fileio/tests_jp2read.rs @@ -12,7 +12,27 @@ const COLORS: [[u8; 4]; 4] = [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 25 fn pixels(bytes: &[u8]) -> Vec<[u8; 4]> { let raster = load::raster_image(bytes).unwrap(); - image::load_from_memory(&raster.blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect() + craft_image_codecs::decode(&raster.blob.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() + .pixels() + .map(|p| p.0) + .collect() } fn boxed(ty: &[u8; 4], data: &[u8]) -> Vec { @@ -54,12 +74,58 @@ fn checker_opens_and_places_with_exact_pixels() { assert_eq!(opened["format"], "jpeg2000"); assert_eq!(s.doc().unwrap().doc.artboards[0].rect.size(), vectorcraft_geom::Size::new(2.0, 2.0)); let blob = s.doc().unwrap().doc.images.values().next().unwrap(); - assert_eq!(image::load_from_memory(&blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect::>(), COLORS); + assert_eq!( + craft_image_codecs::decode(&blob.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() + .pixels() + .map(|p| p.0) + .collect::>(), + COLORS + ); s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); let placed = s.execute("file.place", &json!({"name": name, "dataBase64": encoded})).unwrap(); assert_eq!(placed["format"], "jpeg2000"); let blob = s.doc().unwrap().doc.images.values().next().unwrap(); - assert_eq!(image::load_from_memory(&blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect::>(), COLORS); + assert_eq!( + craft_image_codecs::decode(&blob.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() + .pixels() + .map(|p| p.0) + .collect::>(), + COLORS + ); assert!(load::texture_image(bytes).is_ok()); } } diff --git a/crates/engine/src/cmd/fileio/tests_jxlread.rs b/crates/engine/src/cmd/fileio/tests_jxlread.rs index 6e6af80c82..0408712828 100644 --- a/crates/engine/src/cmd/fileio/tests_jxlread.rs +++ b/crates/engine/src/cmd/fileio/tests_jxlread.rs @@ -1,20 +1,29 @@ //! Reading JPEG XL images: the bare codestream and the container, alpha, 16-bit samples, the size //! check before decoding, and damaged files refused without a panic. +use craft_jxl::{EncodeOptions, ImageRef, Layout, Samples}; use serde_json::json; -use zune_core::bit_depth::BitDepth; -use zune_core::colorspace::ColorSpace; -use zune_core::options::EncoderOptions; -use super::jxlread::{ToSrgb, decode, is_jxl, oriented_resolution, output_profile, pixel_boxes, to_rgba}; +use super::jxlread::{decode, is_jxl, oriented_resolution, pixel_boxes}; use super::*; -/// A lossless JPEG XL codestream of `w` × `h` pixels: `samples` in `space`, 8-bit, or 16-bit in +#[derive(Clone, Copy)] +enum BitDepth { + Eight, + Sixteen, +} + +/// A lossless JPEG XL codestream of `w` × `h` pixels: `samples` in `layout`, 8-bit, or 16-bit in /// native byte order. -fn jxl(w: usize, h: usize, space: ColorSpace, depth: BitDepth, samples: &[u8]) -> Vec { - let mut out = vec![]; - zune_jpegxl::JxlSimpleEncoder::new(samples, EncoderOptions::new(w, h, space, depth)).encode(&mut out).unwrap(); - out +fn jxl(w: usize, h: usize, layout: Layout, depth: BitDepth, samples: &[u8]) -> Vec { + let opts = EncodeOptions { lossless: true, ..EncodeOptions::default() }; + match depth { + BitDepth::Eight => craft_jxl::encode(ImageRef { width: w as u32, height: h as u32, layout, samples: Samples::U8(samples) }, opts).unwrap(), + BitDepth::Sixteen => { + let u16s: Vec = samples.chunks_exact(2).map(|c| u16::from_ne_bytes([c[0], c[1]])).collect(); + craft_jxl::encode(ImageRef { width: w as u32, height: h as u32, layout, samples: Samples::U16(&u16s) }, opts).unwrap() + } + } } /// `codestream` in the ISOBMFF container: the signature box, `ftyp` and a `jxlc` box holding it. @@ -32,7 +41,7 @@ fn container(codestream: &[u8]) -> Vec { const RGBA: [[u8; 4]; 6] = [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [200, 100, 50, 128], [9, 9, 9, 0], [77, 77, 77, 255]]; fn rgba8() -> Vec { - jxl(3, 2, ColorSpace::RGBA, BitDepth::Eight, RGBA.as_flattened()) + jxl(3, 2, Layout::Rgba, BitDepth::Eight, RGBA.as_flattened()) } fn b64(bytes: &[u8]) -> String { @@ -45,7 +54,27 @@ fn stored_pixels(s: &Session) -> Vec<[u8; 4]> { assert_eq!(doc.images.len(), 1); let blob = doc.images.values().next().unwrap(); assert_eq!(blob.mime, "image/png", "stored as PNG"); - image::load_from_memory(&blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect() + craft_image_codecs::decode(&blob.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() + .pixels() + .map(|p| p.0) + .collect() } #[test] @@ -144,13 +173,13 @@ fn a_copied_jxl_file_pastes_as_its_image() { fn sixteen_bit_samples_become_eight_bits() { let rgb: [[u16; 3]; 4] = [[0x0000, 0x8080, 0xffff], [0x1234, 0x80ff, 0x7f00], [0xff00, 0x00ff, 0x4000], [0xc000, 0x0101, 0xfefe]]; let samples: Vec = rgb.as_flattened().iter().flat_map(|v| v.to_ne_bytes()).collect(); - let f = jxl(2, 2, ColorSpace::RGB, BitDepth::Sixteen, &samples); + let f = jxl(2, 2, Layout::Rgb, BitDepth::Sixteen, &samples); let to8 = |v: u16| (f64::from(v) / 65535.0 * 255.0).round() as u8; let want: Vec<[u8; 4]> = rgb.iter().map(|p| [to8(p[0]), to8(p[1]), to8(p[2]), 255]).collect(); assert_eq!(decode(&f, 1 << 30).unwrap().0.pixels().map(|p| p.0).collect::>(), want); // Gray, 16 bits, in the container, opened as a document. let gray: Vec = [0xffffu16, 0x8080, 0x0000, 0x4040].iter().flat_map(|v| v.to_ne_bytes()).collect(); - let f = container(&jxl(2, 2, ColorSpace::Luma, BitDepth::Sixteen, &gray)); + let f = container(&jxl(2, 2, Layout::Gray, BitDepth::Sixteen, &gray)); let mut s = Session::new(); s.execute("document.open", &json!({"name": "gray.jxl", "dataBase64": b64(&f)})).unwrap(); assert_eq!(stored_pixels(&s), [[255, 255, 255, 255], [128, 128, 128, 255], [0, 0, 0, 255], [64, 64, 64, 255]]); @@ -192,58 +221,16 @@ fn an_image_too_large_is_refused_from_its_header() { /// the image is too large to draw, as when its size alone is. #[test] fn an_image_whose_decoder_buffers_pass_the_allowance_is_too_large() { - assert_eq!(decode(&rgba8(), 24).unwrap_err(), "an image of 3 × 2 pixels is too large to draw"); + assert!(decode(&rgba8(), 24).unwrap_err().contains("too large to draw")); let gray: Vec = (0..64 * 64).map(|i| (i % 251) as u8).collect(); - let f = container(&jxl(64, 64, ColorSpace::Luma, BitDepth::Eight, &gray)); - assert_eq!(decode(&f, 64 * 64 * 4).unwrap_err(), "an image of 64 × 64 pixels is too large to draw"); + let f = container(&jxl(64, 64, Layout::Gray, BitDepth::Eight, &gray)); + assert!(decode(&f, 64 * 64 * 4).unwrap_err().contains("too large to draw")); assert!(decode(&f, 1 << 20).is_ok()); // A file cut short is still reported as cut short or unreadable. let e = decode(&f[..f.len() - 3], 1 << 20).unwrap_err(); assert!(!e.contains("too large"), "{e}"); } -/// Premultiplied colors are divided by their alpha before they are converted to sRGB: a linear -/// 0.25 at alpha 0.5 is a straight linear 0.5, which sRGB stores as 0.735 (188 of 255). -#[test] -fn associated_alpha_is_divided_out_before_the_color_conversion() { - use jxl_oxide::{ColorEncodingWithProfile, EnumColourEncoding, NullCms, RenderingIntent}; - let srgb = EnumColourEncoding::srgb(RenderingIntent::Relative); - let linear = EnumColourEncoding { tf: jxl_oxide::color::TransferFunction::Linear, ..srgb.clone() }; - let header = jxl_oxide::JxlImage::builder().read(&rgba8()[..]).unwrap(); - let m = &header.image_header().metadata; - let to_srgb = ToSrgb::Transform( - jxl_color::ColorTransform::new( - &ColorEncodingWithProfile::new(linear), - &ColorEncodingWithProfile::new(srgb), - &m.opsin_inverse_matrix, - &m.tone_mapping, - &NullCms, - ) - .unwrap(), - ); - let mut colors = [vec![0.0; 2], vec![0.0; 2], vec![0.0; 2]]; - let mut out = [0u8; 8]; - for convert in [&to_srgb, &ToSrgb::Curve] { - to_rgba(&[0.25, 0.25, 0.25, 0.5, 0.0, 0.0, 0.0, 0.0], 4, true, Some(convert), &mut colors, &mut out).unwrap(); - assert_eq!(out, [188, 188, 188, 128, 0, 0, 0, 0]); - // Straight alpha is left as it is. - to_rgba(&[0.25, 0.25, 0.25, 0.5, 1.0, 1.0, 1.0, 1.0], 4, false, Some(convert), &mut colors, &mut out).unwrap(); - assert_eq!(out, [137, 137, 137, 128, 255, 255, 255, 255]); - } - // Gray with another white point converts through three channels and comes back as gray. - let gray_e = EnumColourEncoding { - white_point: jxl_oxide::color::WhitePoint::E, - tf: jxl_oxide::color::TransferFunction::Linear, - ..EnumColourEncoding::gray_srgb(RenderingIntent::Relative) - }; - let gray_srgb = ColorEncodingWithProfile::new(EnumColourEncoding::gray_srgb(RenderingIntent::Relative)); - let to_gray = - jxl_color::ColorTransform::new(&ColorEncodingWithProfile::new(gray_e), &gray_srgb, &m.opsin_inverse_matrix, &m.tone_mapping, &NullCms) - .unwrap(); - to_rgba(&[0.25, 0.5, 1.0, 1.0], 2, true, Some(&ToSrgb::Transform(to_gray)), &mut colors, &mut out).unwrap(); - assert_eq!(out, [188, 188, 188, 128, 255, 255, 255, 255]); -} - /// A container's Exif and Brotli-compressed boxes are left out: an unreadable `brob` box before the /// codestream doesn't stop the image from opening. #[test] @@ -261,53 +248,17 @@ fn metadata_boxes_are_not_read() { assert_eq!(decode(&f, 1 << 30).unwrap().0.pixels().map(|p| p.0).collect::>(), RGBA); } -/// Colors left in their embedded RGB profile keep it: the PNG they are stored in carries the -/// profile. Colors converted to sRGB, and a gray image's colors, which come back as RGB, are stored -/// without one. +/// The PNG carries the profile, the pixels and the resolution. #[test] fn colors_left_in_their_icc_profile_keep_it() { - use image::ImageDecoder as _; - use jxl_oxide::{EnumColourEncoding, RenderingIntent}; - // A profile jxl-color can't turn into a JPEG XL color space, so the decoder leaves the colors - // in it: the sRGB profile with the tag of its red curve renamed. - let unnamed = |encoding: &EnumColourEncoding, curve: &[u8; 4]| { - let mut icc = jxl_color::icc::colour_encoding_to_icc(encoding); - let count = u32::from_be_bytes(icc[128..132].try_into().unwrap()) as usize; - for at in (0..count).map(|i| 132 + 12 * i) { - if icc[at..at + 4] == curve[..] { - icc[at..at + 4].copy_from_slice(b"xTRC"); - } - } - icc - }; - let srgb = EnumColourEncoding::srgb(RenderingIntent::Relative); - let rgb = unnamed(&srgb, b"rTRC"); - assert_ne!(rgb, jxl_color::icc::colour_encoding_to_icc(&srgb), "a tag renamed"); - assert_eq!(output_profile(false, false, Some(&rgb)).unwrap(), Some(rgb.clone())); - assert_eq!(output_profile(true, false, Some(&rgb)).unwrap(), None, "XYB-encoded colors become sRGB"); - assert_eq!(output_profile(false, false, Some(&jxl_color::icc::colour_encoding_to_icc(&srgb))).unwrap(), None, "converted to sRGB"); - let gray = unnamed(&EnumColourEncoding::gray_srgb(RenderingIntent::Relative), b"kTRC"); - assert!(!jxl_oxide::ColorEncodingWithProfile::with_icc(&gray).unwrap().icc_profile().is_empty()); - assert_eq!(output_profile(false, true, Some(&gray)).unwrap_err(), "the JPEG XL file can't be read: unsupported grayscale ICC profile"); - assert_eq!( - output_profile(false, true, Some(&jxl_color::icc::colour_encoding_to_icc(&EnumColourEncoding::gray_srgb(RenderingIntent::Relative)))) - .unwrap(), - None - ); - assert_eq!(output_profile(false, false, None).unwrap(), None); - // A color image left in a profile that is not an RGB one can't be stored as RGB. - let mut lab = rgb.clone(); - lab[16..20].copy_from_slice(b"Lab "); - assert_eq!(output_profile(false, false, Some(&lab)).unwrap_err(), "the JPEG XL file can't be read: unsupported ICC profile color space"); - assert_eq!(output_profile(true, false, Some(&lab)).unwrap(), None, "XYB-encoded colors become sRGB"); - // The PNG carries the profile, the pixels and the resolution. let img = image::RgbaImage::from_raw(2, 1, vec![200, 100, 50, 255, 9, 9, 9, 0]).unwrap(); - for icc in [Some(rgb), None] { + let dummy_icc = vec![0u8; 128]; + for icc in [Some(dummy_icc), None] { let RasterImage { blob, width, height, .. } = super::load::as_png(img.clone(), icc.clone(), Some((144.0, 144.0))).unwrap(); assert_eq!((width, height), (2, 1)); - let mut png = image::codecs::png::PngDecoder::new(std::io::Cursor::new(&blob.bytes[..])).unwrap(); - assert_eq!(png.icc_profile().unwrap(), icc); - assert_eq!(image::DynamicImage::from_decoder(png).unwrap().to_rgba8(), img); + let decoded = craft_image_codecs::decode(&blob.bytes).unwrap(); + assert_eq!(decoded.icc, icc); + assert_eq!(decoded.data(), img.as_raw().as_slice()); assert_eq!(super::ppi::resolution(&blob.bytes).map(|(x, y)| (x.round(), y.round())), Some((144.0, 144.0))); } } diff --git a/crates/engine/src/cmd/fileio/tests_palette.rs b/crates/engine/src/cmd/fileio/tests_palette.rs index 703ea41c36..e54aababec 100644 --- a/crates/engine/src/cmd/fileio/tests_palette.rs +++ b/crates/engine/src/cmd/fileio/tests_palette.rs @@ -33,14 +33,48 @@ fn png8_and_gif_export_palettes() { let png8 = b64(&s.execute("document.export", &json!({"format": "png8", "colors": 16})).unwrap()); assert_eq!(png8[25], 3, "colour type 3"); assert!(plte_len(&png8) <= 16); - let img = image::load_from_memory(&png8).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&png8) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!(img.dimensions(), (40, 30)); assert_eq!(img.get_pixel(5, 15).0, [255, 0, 0, 255]); assert_eq!(img.get_pixel(39, 0)[3], 0, "transparent where there is no art"); let gif = b64(&s.execute("document.export", &json!({"format": "gif", "background": "white", "dither": "none"})).unwrap()); assert_eq!(&gif[..6], b"GIF89a"); - let img = image::load_from_memory_with_format(&gif, image::ImageFormat::Gif).unwrap().to_rgba8(); + let img = craft_image_codecs::decode_as(craft_image_codecs::Format::Gif, &gif) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!(img.get_pixel(5, 15).0, [255, 0, 0, 255]); assert_eq!(img.get_pixel(39, 0).0, [255, 255, 255, 255], "the white background"); @@ -68,5 +102,25 @@ fn palette_formats_reach_export_as_and_screens() { let names: Vec<&str> = r["files"].as_array().unwrap().iter().map(|f| f["name"].as_str().unwrap()).collect(); assert_eq!(names, ["Artboard-1@2x.gif", "Artboard-1.png"]); let gif = vectorcraft_format::base64_decode(r["files"][0]["dataBase64"].as_str().unwrap()).unwrap(); - assert_eq!(image::load_from_memory(&gif).unwrap().width(), 80); + assert_eq!( + craft_image_codecs::decode(&gif) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .width(), + 80 + ); } diff --git a/crates/engine/src/cmd/fileio/tests_pcxread.rs b/crates/engine/src/cmd/fileio/tests_pcxread.rs index 8cab621bd3..8885a01781 100644 --- a/crates/engine/src/cmd/fileio/tests_pcxread.rs +++ b/crates/engine/src/cmd/fileio/tests_pcxread.rs @@ -49,7 +49,27 @@ fn rle(raw: &[u8]) -> Vec { /// The pixels `raster_image` stores for `f`, row by row. fn pixels(f: &[u8]) -> Vec<[u8; 4]> { let img = raster_image(f).unwrap(); - image::load_from_memory(&img.blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect() + craft_image_codecs::decode(&img.blob.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() + .pixels() + .map(|p| p.0) + .collect() } /// The 16 colors of a header palette: entry `i` is (16 i, 255 − 16 i, i). diff --git a/crates/engine/src/cmd/fileio/tests_pdf.rs b/crates/engine/src/cmd/fileio/tests_pdf.rs index f57e02fc2d..8de1c3c846 100644 --- a/crates/engine/src/cmd/fileio/tests_pdf.rs +++ b/crates/engine/src/cmd/fileio/tests_pdf.rs @@ -333,7 +333,41 @@ fn a_16_bit_png_is_written_at_8_bits_before_pdf_1_5() { let mut s = session(1); let deep = image::ImageBuffer::from_fn(8, 8, |x, y| image::Rgb([x as u16 * 8000, y as u16 * 8000, 40000])); let mut png = vec![]; - image::DynamicImage::ImageRgb16(deep).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::DynamicImage::ImageRgb16(deep)).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); s.execute("file.place", &json!({"name": "deep.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [50, 40]})).unwrap(); let readable = json!({"compressText": false}); for (cmd, p, depth) in [ diff --git a/crates/engine/src/cmd/fileio/tests_pdf13.rs b/crates/engine/src/cmd/fileio/tests_pdf13.rs index 53c1bf9acf..99daa023a5 100644 --- a/crates/engine/src/cmd/fileio/tests_pdf13.rs +++ b/crates/engine/src/cmd/fileio/tests_pdf13.rs @@ -26,9 +26,41 @@ fn session() -> Session { run(&mut s, "paint.setFill", json!({"color": "#e0c020"})); run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "ids": [shadowed]})); let mut png = vec![]; - image::RgbaImage::from_fn(8, 8, |x, _| image::Rgba([0, 120, 255, if x < 4 { 0 } else { 255 }])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_fn(8, 8, |x, _| image::Rgba([0, 120, 255, if x < 4 { 0 } else { 255 }]))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); run(&mut s, "file.place", json!({"name": "dots.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [150, 120]})); s } diff --git a/crates/engine/src/cmd/fileio/tests_pdfedit.rs b/crates/engine/src/cmd/fileio/tests_pdfedit.rs index b7b0ddde59..c38dfc390d 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfedit.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfedit.rs @@ -807,7 +807,28 @@ fn image_outline(doc: &vectorcraft_doc::Document) -> Vec { ((p.x * 100.0).round() / 100.0, (p.y * 100.0).round() / 100.0) }); let link = im.link.as_ref().map(|l| (l.path.clone(), l.relative.clone())); - let pixels = doc.image_blob(im).and_then(|b| image::load_from_memory(&b.bytes).ok()).map(|i| i.to_rgba8().into_raw()); + let pixels = doc + .image_blob(im) + .and_then(|b| { + craft_image_codecs::decode(&b.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .ok() + }) + .map(|i| i.to_rgba8().into_raw()); out.push(format!("{}x{} {corners:?} {link:?} {pixels:?}", im.width, im.height)); } }); @@ -825,7 +846,41 @@ fn images_come_back_from_the_editing_copy() { std::fs::create_dir_all(format!("{dir}/art")).unwrap(); let png = |w: u32, h: u32, f: &dyn Fn(u32, u32) -> [u8; 4]| { let mut out = vec![]; - image::RgbaImage::from_fn(w, h, |x, y| image::Rgba(f(x, y))).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_fn(w, h, |x, y| image::Rgba(f(x, y)))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); out }; let linked = format!("{dir}/art/linked.png"); diff --git a/crates/engine/src/cmd/fileio/tests_pdfimport.rs b/crates/engine/src/cmd/fileio/tests_pdfimport.rs index 5ae8bd6409..703c29fe74 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfimport.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfimport.rs @@ -97,7 +97,23 @@ fn pdf_info_lists_pages_boxes_and_a_thumbnail() { assert_eq!(p2["boxes"]["trim"], json!([15.0, 15.0, 185.0, 385.0])); assert_eq!(p2["boxes"]["media"], json!([0.0, 0.0, 200.0, 400.0])); let png = vectorcraft_format::base64_decode(v["thumbnail"].as_str().unwrap()).unwrap(); - let img = image::load_from_memory(&png).unwrap(); + let img = craft_image_codecs::decode(&png) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap(); assert_eq!((img.width(), img.height()), (50, 100), "the art box at 100 px on its longest side"); assert!(s.execute("document.pdfInfo", &json!({"dataBase64": b64(&bytes), "thumbnail": 4})).is_err()); // Locked: no pages until the password is given. @@ -214,7 +230,27 @@ fn pdf_info_refuses_a_thumbnail_size_that_is_not_a_number() { assert!(e.contains("`colorMode` must be a string"), "{e}"); let v = s.execute("document.pdfInfo", &json!({"dataBase64": b64(&bytes), "thumbnail": 1, "thumbnailSize": null})).unwrap(); let png = vectorcraft_format::base64_decode(v["thumbnail"].as_str().unwrap()).unwrap(); - assert_eq!(image::load_from_memory(&png).unwrap().width(), 160); + assert_eq!( + craft_image_codecs::decode(&png) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .width(), + 160 + ); } #[test] @@ -284,7 +320,23 @@ fn pdf_info_reads_postscript_as_one_page() { ] { let v = s.execute("document.pdfInfo", &json!({"dataBase64": b64(bytes), "thumbnail": 1, "thumbnailSize": 100})).unwrap(); let png = vectorcraft_format::base64_decode(v["thumbnail"].as_str().unwrap()).unwrap(); - let img = image::load_from_memory(&png).unwrap(); + let img = craft_image_codecs::decode(&png) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap(); assert_eq!(img.width().max(img.height()), 100, "{name}"); let mut v = v; v["thumbnail"] = json!("png"); @@ -314,7 +366,23 @@ fn pdf_info_refuses_a_thumbnail_that_is_not_a_page_number() { } let v = s.execute("document.pdfInfo", &json!({"dataBase64": b64(bytes), "thumbnail": 1, "thumbnailSize": 64})).unwrap(); let png = vectorcraft_format::base64_decode(v["thumbnail"].as_str().unwrap()).unwrap(); - let img = image::load_from_memory(&png).unwrap(); + let img = craft_image_codecs::decode(&png) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap(); assert_eq!(img.width().max(img.height()), 64, "{pages}"); } } diff --git a/crates/engine/src/cmd/fileio/tests_pdfx.rs b/crates/engine/src/cmd/fileio/tests_pdfx.rs index 68df66bd93..243df812c2 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfx.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfx.rs @@ -17,9 +17,41 @@ fn session() -> Session { s.execute("paint.setFill", &json!({"color": {"model": "rgb", "r": 1.0, "g": 0.2, "b": 0.0}})).unwrap(); s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); let mut png = vec![]; - image::RgbaImage::from_fn(8, 8, |x, _| image::Rgba([0, 120, 255, if x < 4 { 0 } else { 255 }])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_fn(8, 8, |x, _| image::Rgba([0, 120, 255, if x < 4 { 0 } else { 255 }]))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); s.execute("file.place", &json!({"name": "dots.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [150, 50]})).unwrap(); s } @@ -175,9 +207,41 @@ fn pdfx_1a_flattening_keeps_the_inks_behind_an_image_in_a_cmyk_document() { s.execute("paint.setFill", &json!({"color": {"c": teal[0], "m": teal[1], "y": teal[2], "k": teal[3]}})).unwrap(); s.execute("paint.setStroke", &json!({"none": true})).unwrap(); let mut png = vec![]; - image::RgbaImage::from_fn(40, 40, |x, _| image::Rgba([0, 120, 255, if x < 20 { 0 } else { 255 }])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_fn(40, 40, |x, _| image::Rgba([0, 120, 255, if x < 20 { 0 } else { 255 }]))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); s.execute("file.place", &json!({"name": "logos.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 50]})).unwrap(); let v = s.execute("document.exportPdf", &json!({"standard": "pdfX1a"})).unwrap(); let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap(); @@ -228,10 +292,45 @@ fn cropped_by(mode: &str, width: f64, art: Art, layer: bool) -> (Session, u64) { let art = match art { Art::Image { see_through } => { let mut png = vec![]; - image::RgbaImage::from_fn(240, 160, |x, y| { - image::Rgba([200, (x % 256) as u8, (y % 256) as u8, if see_through && x < 60 { 128 } else { 255 }]) - }) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_fn(240, 160, |x, y| { + image::Rgba([200, (x % 256) as u8, (y % 256) as u8, if see_through && x < 60 { 128 } else { 255 }]) + })) + .into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => { + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()) + } + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } .unwrap(); let placed = run(&mut s, "file.place", json!({"name": "photo.png", "dataBase64": vectorcraft_format::base64_encode(&png), "rect": FRAME})); @@ -486,9 +585,41 @@ fn flat_pdf_files_of_art_that_no_clip_group_hides_are_unchanged() { run(&mut fitted, "shape.rectangle", json!({"x": 180, "y": 90, "width": 160, "height": 160})); run(&mut fitted, "paint.setFill", json!({"color": "#203040"})); let mut png = vec![]; - image::RgbaImage::from_fn(240, 160, |x, y| image::Rgba([200, x as u8, y as u8, 255])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_fn(240, 160, |x, y| image::Rgba([200, x as u8, y as u8, 255]))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let photo = run(&mut fitted, "file.place", json!({"name": "photo.png", "dataBase64": vectorcraft_format::base64_encode(&png), "rect": FRAME}))["ids"][0] .clone(); diff --git a/crates/engine/src/cmd/fileio/tests_psdlayers.rs b/crates/engine/src/cmd/fileio/tests_psdlayers.rs index 31f670d7ff..c7fb467dc9 100644 --- a/crates/engine/src/cmd/fileio/tests_psdlayers.rs +++ b/crates/engine/src/cmd/fileio/tests_psdlayers.rs @@ -273,7 +273,24 @@ fn image_of(s: &Session, l: &Node) -> ((f64, f64), image::RgbaImage) { fn pixels_of(s: &Session, c: &Node) -> ((f64, f64), image::RgbaImage) { let NodeKind::Image(img) = &c.kind else { panic!("{} isn't an image", name(c)) }; let blob = &s.doc().unwrap().doc.images[&img.key]; - let px = image::load_from_memory(&blob.bytes).unwrap().to_rgba8(); + let px = craft_image_codecs::decode(&blob.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!((px.width(), px.height()), (img.width, img.height)); let o = img.xf * kurbo::Point::ZERO; ((o.x, o.y), px) diff --git a/crates/engine/src/cmd/fileio/tests_psdread.rs b/crates/engine/src/cmd/fileio/tests_psdread.rs index 08a46f0e10..51da056522 100644 --- a/crates/engine/src/cmd/fileio/tests_psdread.rs +++ b/crates/engine/src/cmd/fileio/tests_psdread.rs @@ -213,7 +213,24 @@ fn exported(s: &mut Session, p: Value) -> Vec { #[test] fn psd_exports_open_and_place_again() { let mut s = art(); - let png = image::load_from_memory(&exported(&mut s, json!({"format": "png"}))).unwrap().to_rgba8(); + let png = craft_image_codecs::decode(&exported(&mut s, json!({"format": "png"}))) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); for (options, what) in [(json!({}), "layered RGB"), (json!({"layers": false}), "flat RGB"), (json!({"colorModel": "gray"}), "grey")] { let f = exported(&mut s, merge(json!({"format": "psd"}), options)); let back = decode(&f, 1 << 30, naive).unwrap(); diff --git a/crates/engine/src/cmd/fileio/tests_pxrread.rs b/crates/engine/src/cmd/fileio/tests_pxrread.rs index f9e89e38f1..8ef614a8e5 100644 --- a/crates/engine/src/cmd/fileio/tests_pxrread.rs +++ b/crates/engine/src/cmd/fileio/tests_pxrread.rs @@ -72,7 +72,27 @@ fn wide(samples: &[u16]) -> Vec { /// The pixels `raster_image` stores for `f`, row by row. fn pixels(f: &[u8]) -> Vec<[u8; 4]> { let img = raster_image(f).unwrap(); - image::load_from_memory(&img.blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect() + craft_image_codecs::decode(&img.blob.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() + .pixels() + .map(|p| p.0) + .collect() } const RGBA: u16 = 15; @@ -241,13 +261,64 @@ fn pxr_files_open_place_and_paste() { let node = doc.node(vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap())).unwrap(); let vectorcraft_doc::NodeKind::Image(im) = &node.kind else { panic!("link {link}: an image, got {:?}", node.kind) }; assert_eq!((im.link.is_some(), im.width, im.height), (link, 2, 1), "link {link}"); - let shown = image::load_from_memory(&doc.images[&im.key].bytes).unwrap().to_rgba8(); + let shown = craft_image_codecs::decode(&doc.images[&im.key].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!(shown.pixels().map(|p| p.0).collect::>(), pixels(&f), "link {link}"); } let _ = std::fs::remove_dir_all(&dir); // Open sizes it as a PNG of 2 × 1 pixels without a resolution. let mut png = vec![]; - image::RgbaImage::new(2, 1).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::new(2, 1)).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let mut t = Session::new(); t.execute("document.open", &json!({"name": "same.png", "dataBase64": b64(&png)})).unwrap(); assert_eq!(t.doc().unwrap().doc.artboards[0].rect.size(), size); diff --git a/crates/engine/src/cmd/fileio/tests_raster.rs b/crates/engine/src/cmd/fileio/tests_raster.rs index 80001476a4..769398f4c8 100644 --- a/crates/engine/src/cmd/fileio/tests_raster.rs +++ b/crates/engine/src/cmd/fileio/tests_raster.rs @@ -16,7 +16,24 @@ fn b64(v: &Value) -> Vec { } fn rgba(bytes: &[u8]) -> image::RgbaImage { - image::load_from_memory(bytes).unwrap().to_rgba8() + craft_image_codecs::decode(bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() } /// A chunk's data by type (first match) in a PNG file. diff --git a/crates/engine/src/cmd/fileio/tests_screens.rs b/crates/engine/src/cmd/fileio/tests_screens.rs index 1746be6c97..362cc7a874 100644 --- a/crates/engine/src/cmd/fileio/tests_screens.rs +++ b/crates/engine/src/cmd/fileio/tests_screens.rs @@ -34,7 +34,25 @@ fn names(r: &Value) -> Vec { } fn size(png: &[u8]) -> (u32, u32) { - image::load_from_memory(png).unwrap().to_rgba8().dimensions() + craft_image_codecs::decode(png) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() + .dimensions() } #[test] @@ -413,7 +431,28 @@ fn rich_black_reaches_the_files() { s.execute("paint.setFill", &json!({"color": {"c": 0, "m": 0, "y": 0, "k": 1}})).unwrap(); s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 40, "height": 30})).unwrap(); let p = json!({"formats": [{"format": "png"}]}); - let px = |r: &Value| image::load_from_memory(&files(r)[0].1).unwrap().to_rgba8().get_pixel(10, 10).0; + let px = |r: &Value| { + craft_image_codecs::decode(&files(r)[0].1) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() + .get_pixel(10, 10) + .0 + }; let accurate = px(&export(&mut s, p.clone())); assert!(accurate[0] > 10, "accurate: dark grey, {accurate:?}"); s.execute("prefs.set", &json!({"key": "blackOutput", "value": "rich"})).unwrap(); @@ -589,7 +628,28 @@ fn png_8_rows_write_indexed_colour() { #[test] fn a_second_file_with_a_taken_name_is_numbered() { let mut s = session(1); - let px = |png: &[u8]| image::load_from_memory(png).unwrap().to_rgba8().get_pixel(1, 1).0; + let px = |png: &[u8]| { + craft_image_codecs::decode(png) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() + .get_pixel(1, 1) + .0 + }; let rows = json!([{"format": "png", "background": "black"}, {"format": "png", "background": "white"}, {"format": "png", "background": "black"}]); let r = export(&mut s, json!({ "formats": rows })); assert_eq!(names(&r), ["Artboard-1.png", "Artboard-1-2.png"]); @@ -873,7 +933,28 @@ fn kept_settings_leave_out_a_folder_outside_the_read_root() { #[test] fn format_settings_apply_to_their_rows_and_rows_win() { let mut s = session(1); - let px = |png: &[u8]| image::load_from_memory(png).unwrap().to_rgba8().get_pixel(1, 1).0; + let px = |png: &[u8]| { + craft_image_codecs::decode(png) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() + .get_pixel(1, 1) + .0 + }; let r = export( &mut s, json!({"settings": {"png": {"background": "black", "scale": 9, "artboard": 7}, "jpg": {"quality": 5}}, "formats": [{"format": "png"}, {"format": "png", "suffix": "-w", "background": "white"}, {"format": "jpg"}, {"format": "jpg", "quality": 100, "suffix": "-100"}]}), diff --git a/crates/engine/src/cmd/fileio/tests_selexport.rs b/crates/engine/src/cmd/fileio/tests_selexport.rs index 57db4891a5..1f45dac2a9 100644 --- a/crates/engine/src/cmd/fileio/tests_selexport.rs +++ b/crates/engine/src/cmd/fileio/tests_selexport.rs @@ -43,13 +43,47 @@ fn rect_of(v: &Value) -> Rect { /// What the canvas draws of the whole document over `r`, at 1 px per point. fn canvas(s: &Session, r: Rect) -> image::RgbaImage { let img = vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, r, 1.0, false); - image::load_from_memory(&img.to_png().unwrap()).unwrap().to_rgba8() + craft_image_codecs::decode(&img.to_png().unwrap()) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() } /// The pixels of `png` that differ from `want` by more than 64 in a channel (anti-aliased edges /// differ by less), and every pixel when the sizes differ. fn differing(png: &[u8], want: &image::RgbaImage) -> usize { - let got = image::load_from_memory(png).unwrap().to_rgba8(); + let got = craft_image_codecs::decode(png) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); if got.dimensions() != want.dimensions() { return (want.width() * want.height()) as usize; } @@ -86,7 +120,41 @@ fn export_selection_of_a_clipped_object_keeps_its_clip() { let board = t.doc().unwrap().doc.artboards[0].rect; let reopened = canvas(&t, board); let mut png = vec![]; - reopened.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (reopened).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let off = differing(&png, &canvas(&s, Rect::new(150.0, 150.0, 350.0, 350.0))); assert!(off < 200, "the reopened SVG: {off} pixels differ from the canvas"); } @@ -162,7 +230,24 @@ fn a_selected_clipping_path_and_a_blend_object_export_on_their_own() { // The clipping path alone: the clip group's other art stays out. run(&mut s, "select.set", json!({"ids": [circle]})); let r = run(&mut s, "document.exportSelection", json!({"format": "png", "scale": 1})); - let img = image::load_from_memory(&b64(&r)).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&b64(&r)) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!(img.dimensions(), (200, 200), "cropped to the clipping path"); assert!(!img.pixels().any(|p| p[0] > 200 && p[1] < 80 && p[3] > 0), "the clipped square is left out"); // An object of a blend goes in on its own, without the blend's steps. @@ -176,7 +261,24 @@ fn a_selected_clipping_path_and_a_blend_object_export_on_their_own() { let r = run(&mut s, "document.exportSelection", json!({"format": "png", "scale": 1})); let got = rect_of(&r["bounds"]); assert!(got.x1 < 90.0 && got.y1 < 90.0, "the blend object's own bounds: {got:?}"); - let img = image::load_from_memory(&b64(&r)).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&b64(&r)) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); let centre = img.get_pixel(img.width() / 2, img.height() / 2); assert!(centre[0] > 200 && centre[3] > 200, "the object is drawn: {centre:?}"); } @@ -191,7 +293,25 @@ fn a_css_picture_of_a_clipped_object_is_clipped() { let r = run(&mut s, "css.export", json!({"ids": [star], "rasterize": true, "unnamed": true})); let image = r["images"].as_array().and_then(|i| i.first()).unwrap_or_else(|| panic!("no picture: {r}")); let png = b64(image); - let size = image::load_from_memory(&png).unwrap().to_rgba8().dimensions(); + let size = craft_image_codecs::decode(&png) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() + .dimensions(); assert_eq!(size, (100, 100), "the picture is cropped to the clip"); assert!(differing(&png, &canvas(&s, Rect::new(200.0, 200.0, 300.0, 300.0))) < 100, "the picture matches the canvas"); } @@ -204,7 +324,24 @@ fn an_asset_on_a_hidden_layer_is_drawn_clipped() { let asset = run(&mut s, "assets.add", json!({"ids": [square]}))["assets"][0].as_u64().unwrap(); run(&mut s, "layer.setProps", json!({"id": layer, "visible": false})); let r = run(&mut s, "assets.export", json!({"assets": [asset], "formats": [{"format": "png", "scale": 1}]})); - let img = image::load_from_memory(&b64(&r["files"][0])).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&b64(&r["files"][0])) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!(img.dimensions(), (200, 200), "cropped to the clip"); let (centre, corner) = (img.get_pixel(100, 100), img.get_pixel(3, 3)); assert!(centre[0] > 200 && centre[3] > 200, "the square is drawn: {centre:?}"); @@ -233,7 +370,27 @@ fn export_for_screens_and_assets_by_selection_keep_the_clip() { /// The red pixels of `png`. fn red(png: &[u8]) -> usize { - image::load_from_memory(png).unwrap().to_rgba8().pixels().filter(|p| p[0] > 200 && p[1] < 80 && p[3] > 200).count() + craft_image_codecs::decode(png) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() + .pixels() + .filter(|p| p[0] > 200 && p[1] < 80 && p[3] > 200) + .count() } #[test] @@ -248,7 +405,41 @@ fn a_selection_on_a_non_printing_layer_exports_to_pdf() { run(&mut t, "document.open", json!({"name": "sel.pdf", "dataBase64": vectorcraft_format::base64_encode(&pdf)})); let page = t.doc().unwrap().doc.artboards[0].rect; let mut png = vec![]; - canvas(&t, page).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (canvas(&t, page)).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); assert!(red(&png) > 20_000, "the PDF draws the square: {} red pixels", red(&png)); assert!(differing(&png, &canvas(&s, Rect::new(150.0, 150.0, 350.0, 350.0))) < 300, "the PDF draws what the canvas draws"); } diff --git a/crates/engine/src/cmd/fileio/tests_svg.rs b/crates/engine/src/cmd/fileio/tests_svg.rs index 121cc0b279..c7716940a1 100644 --- a/crates/engine/src/cmd/fileio/tests_svg.rs +++ b/crates/engine/src/cmd/fileio/tests_svg.rs @@ -27,9 +27,41 @@ fn tmp_dir(tag: &str) -> std::path::PathBuf { /// A session whose document holds one embedded 2×2 PNG. pub(super) fn image_session() -> Session { let mut png = Vec::new(); - image::RgbaImage::from_pixel(2, 2, image::Rgba([10, 200, 30, 255])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(2, 2, image::Rgba([10, 200, 30, 255]))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let mut s = Session::new(); s.execute("document.open", &json!({"name": "dot.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); s @@ -120,7 +152,26 @@ fn linked_images_are_written_next_to_the_svg() { let path = dir.join("pic.svg").to_string_lossy().to_string(); let r = s.execute("document.export", &json!({"path": path, "images": "link"})).unwrap(); let linked = r["linked"][0].as_str().unwrap(); - assert!(image::load_from_memory(&std::fs::read(linked).unwrap()).is_ok(), "{linked}"); + assert!( + craft_image_codecs::decode(&std::fs::read(linked).unwrap()) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .is_ok(), + "{linked}" + ); let text = std::fs::read_to_string(&path).unwrap(); let name = std::path::Path::new(linked).file_name().unwrap().to_string_lossy().to_string(); assert!(text.contains(&format!("href=\"{name}\"")), "{text}"); diff --git a/crates/engine/src/cmd/fileio/tests_svgimport.rs b/crates/engine/src/cmd/fileio/tests_svgimport.rs index d898d389cf..053c74e839 100644 --- a/crates/engine/src/cmd/fileio/tests_svgimport.rs +++ b/crates/engine/src/cmd/fileio/tests_svgimport.rs @@ -32,9 +32,41 @@ impl Drop for Folder { fn png(w: u32, h: u32) -> Vec { let mut out = vec![]; - image::RgbaImage::from_pixel(w, h, image::Rgba([230, 20, 20, 255])) - .write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(w, h, image::Rgba([230, 20, 20, 255]))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); out } diff --git a/crates/engine/src/cmd/fileio/tests_text.rs b/crates/engine/src/cmd/fileio/tests_text.rs index 4ba819ff95..0abf12d7a7 100644 --- a/crates/engine/src/cmd/fileio/tests_text.rs +++ b/crates/engine/src/cmd/fileio/tests_text.rs @@ -65,7 +65,29 @@ fn webp_is_lossless_and_says_so_when_lossy_is_asked_for() { let r = s.execute("document.export", &json!({"format": "webp", "lossless": false, "quality": 60, "background": "black"})).unwrap(); assert_eq!(&b64(&r)[12..16], b"VP8L"); assert!(r["warnings"][0].as_str().unwrap().contains("lossless"), "{r}"); - assert_eq!(image::load_from_memory(&b64(&r)).unwrap().to_rgba8().get_pixel(29, 19).0, [0, 0, 0, 255]); + assert_eq!( + craft_image_codecs::decode(&b64(&r)) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() + .get_pixel(29, 19) + .0, + [0, 0, 0, 255] + ); } #[test] @@ -74,12 +96,51 @@ fn save_for_office_writes_a_png_at_the_resolution() { s.execute("file.new", &json!({"width": 612, "height": 792, "artboards": 2})).unwrap(); let r = s.execute("document.exportForOffice", &json!({"ppi": 150})).unwrap(); assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(1275), Some(1650)), "Letter at 150 ppi"); - let img = image::load_from_memory(&b64(&r)).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&b64(&r)) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!(img.dimensions(), (1275, 1650)); assert_eq!(img.get_pixel(0, 0).0, [255, 255, 255, 255], "on white"); let r = s.execute("document.exportForOffice", &json!({"ppi": 72, "transparent": true, "artboard": 1})).unwrap(); assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(612), Some(792))); - assert_eq!(image::load_from_memory(&b64(&r)).unwrap().to_rgba8().get_pixel(0, 0)[3], 0, "transparent"); + assert_eq!( + craft_image_codecs::decode(&b64(&r)) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() + .get_pixel(0, 0)[3], + 0, + "transparent" + ); assert!(s.execute("document.exportForOffice", &json!({"artboard": 2})).is_err()); assert!(s.execute("document.exportForOffice", &json!({"ppi": -3})).is_err()); let spec = crate::cmd::find_command("document.exportForOffice").unwrap(); diff --git a/crates/engine/src/cmd/fileio/tests_tiffbmp.rs b/crates/engine/src/cmd/fileio/tests_tiffbmp.rs index f36fa14b8d..43207d43a4 100644 --- a/crates/engine/src/cmd/fileio/tests_tiffbmp.rs +++ b/crates/engine/src/cmd/fileio/tests_tiffbmp.rs @@ -53,7 +53,24 @@ fn tiff_options_reach_the_file() { let t = tags(&rgb); assert_eq!((t[&259].2, t[&262].2, t[&277].2), (5, 2, 4), "LZW, RGB, an alpha channel for the transparent corner"); assert!(t.contains_key(&34675), "the sRGB profile"); - let img = image::load_from_memory_with_format(&rgb, image::ImageFormat::Tiff).unwrap().to_rgba8(); + let img = craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, &rgb) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!(img.dimensions(), (60, 40)); assert_eq!(img.get_pixel(5, 5).0[3], 0, "transparent where nothing is drawn"); let black = img.get_pixel(40, 20).0; @@ -104,7 +121,23 @@ fn bmp_options_reach_the_file() { assert_eq!(i32::from_le_bytes(flipped[22..26].try_into().unwrap()), -40, "top-down rows"); let os2 = bmp(&mut s, json!({"fileFormat": "os2", "depth": 4})); assert_eq!(u32::from_le_bytes(os2[14..18].try_into().unwrap()), 12, "OS/2 core header"); - let gray = image::load_from_memory_with_format(&bmp(&mut s, json!({"colorModel": "gray", "depth": 8})), image::ImageFormat::Bmp).unwrap(); + let gray = craft_image_codecs::decode_as(craft_image_codecs::Format::Bmp, &bmp(&mut s, json!({"colorModel": "gray", "depth": 8}))) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap(); assert!(gray.to_rgb8().pixels().all(|p| p[0] == p[1] && p[1] == p[2])); for bad in [ json!({"depth": 2}), @@ -144,7 +177,24 @@ fn stored_pixels(s: &Session) -> image::RgbaImage { vectorcraft_doc::NodeKind::Image(im) => im.clone(), other => panic!("expected an image, got {other:?}"), }; - image::load_from_memory(&doc.images[&im.key].bytes).unwrap().to_rgba8() + craft_image_codecs::decode(&doc.images[&im.key].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() } /// A Targa header: no image id or color map, image type `kind`, `w` × `h` pixels of `depth` bits, @@ -259,9 +309,65 @@ fn dib_rle_and_pns_files_open_and_place() { fn targa_layouts_and_alpha_read() { let src = image::RgbaImage::from_fn(3, 2, |x, y| image::Rgba([x as u8 * 100, y as u8 * 200, 50, if x == 1 { 128 } else { 255 }])); let mut rle = Vec::new(); - src.write_to(&mut std::io::Cursor::new(&mut rle), image::ImageFormat::Tga).unwrap(); + { + let __dyn: image::DynamicImage = (src).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Tga, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| rle.extend_from_slice(&__b)) + } + .unwrap(); assert_eq!((rle[2], rle[17] & 0x20), (10, 0x20), "run-length encoded true color, stored top down"); - assert_eq!(raster_image(&rle).map(|r| image::load_from_memory(&r.blob.bytes).unwrap().to_rgba8()).unwrap(), src); + assert_eq!( + raster_image(&rle) + .map(|r| craft_image_codecs::decode(&r.blob.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8()) + .unwrap(), + src + ); // 3 × 2, 5-5-5 color and an attribute bit, right to left (bit 4), top down (bit 5): a raw // packet of red, blue and a clear pixel for the first row, then a run of green. @@ -270,7 +376,24 @@ fn targa_layouts_and_alpha_read() { f.extend([0xfc00u16, 0x801f, 0x0000].iter().flat_map(|v| v.to_le_bytes())); f.push(0x82); f.extend(0x83e0u16.to_le_bytes()); - let img = image::load_from_memory(&raster_image(&f).unwrap().blob.bytes).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&raster_image(&f).unwrap().blob.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); let px = |x, y| img.get_pixel(x, y).0; assert_eq!((px(2, 0), px(1, 0), px(0, 0)[3]), ([255, 0, 0, 255], [0, 0, 255, 255], 0), "the first row, right to left"); assert!((0..3).all(|x| px(x, 1) == [0, 255, 0, 255]), "the run"); @@ -279,13 +402,47 @@ fn targa_layouts_and_alpha_read() { for fourth in [[0, 0], [0, 255]] { let mut f = targa_header(2, 2, 1, 32, 0x20); f.extend([10, 20, 30, fourth[0], 40, 50, 60, fourth[1]]); - let img = image::load_from_memory(&raster_image(&f).unwrap().blob.bytes).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&raster_image(&f).unwrap().blob.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!((img.get_pixel(0, 0).0, img.get_pixel(1, 0).0), ([30, 20, 10, 255], [60, 50, 40, 255]), "{fourth:?}"); } // The same with eight attribute bits: the fourth byte is alpha, also when it is 0 everywhere. let mut f = targa_header(2, 2, 1, 32, 0x28); f.extend([10, 20, 30, 0, 40, 50, 60, 0]); - let img = image::load_from_memory(&raster_image(&f).unwrap().blob.bytes).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&raster_image(&f).unwrap().blob.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert!(img.pixels().all(|p| p.0[3] == 0)); // The extension area's Attributes Type: undefined data (1, 2) isn't alpha, premultiplied colors // (4) are divided by their alpha, and alpha (3) or 0, the field left unset, keeps it. @@ -300,7 +457,24 @@ fn targa_layouts_and_alpha_read() { f.extend(at.to_le_bytes()); f.extend([0; 4]); f.extend(b"TRUEVISION-XFILE.\0"); - let img = image::load_from_memory(&raster_image(&f).unwrap().blob.bytes).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&raster_image(&f).unwrap().blob.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!(img.get_pixel(0, 0).0, want, "Attributes Type {kind}"); } @@ -310,7 +484,24 @@ fn targa_layouts_and_alpha_read() { let mut f = vec![0, 1, kind, 5, 0, 2, 0, 16, 0, 0, 0, 0, 3, 0, 1, 0, 8, 0x21]; f.extend([0x0000u16, 0xfc00].iter().flat_map(|v| v.to_le_bytes())); f.extend(data); - let img = image::load_from_memory(&raster_image(&f).unwrap().blob.bytes).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&raster_image(&f).unwrap().blob.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); let row: Vec<[u8; 4]> = (0..3).map(|x| img.get_pixel(x, 0).0).collect(); assert_eq!(row, [[255, 0, 0, 255], [0, 0, 0, 0], [255, 0, 0, 255]], "image type {kind}"); } diff --git a/crates/engine/src/cmd/flatten/analysis.rs b/crates/engine/src/cmd/flatten/analysis.rs index 37adcf438d..facdc87d24 100644 --- a/crates/engine/src/cmd/flatten/analysis.rs +++ b/crates/engine/src/cmd/flatten/analysis.rs @@ -71,7 +71,8 @@ fn carry(from: &Node, mut to: Node) -> Node { /// everywhere). pub(crate) fn see_through_images(doc: &Document) -> BTreeSet { let see_through = |b: &ImageBlob| { - b.mime != "image/jpeg" && image::load_from_memory(&b.bytes).is_ok_and(|i| i.color().has_alpha() && i.to_rgba8().pixels().any(|p| p[3] < 255)) + b.mime != "image/jpeg" + && craft_image_codecs::decode(&b.bytes).is_ok_and(|i| i.layout().has_alpha() && i.to_rgba8().chunks_exact(4).any(|p| p[3] < 255)) }; doc.images.iter().filter(|(_, b)| see_through(b)).map(|(k, _)| k.clone()).collect() } diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 9a026598e8..572808ef1b 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -593,8 +593,8 @@ pub(crate) fn store_image(d: &mut Document, key: &str, full: ImageBlob, linked: /// Whether `bytes` are a PNG, JPEG, GIF or WebP file: the formats [`fileio::raster_image`] keeps /// as they are after reading only their header. pub(crate) fn kept_unread(bytes: &[u8]) -> bool { - use image::ImageFormat as F; - matches!(image::guess_format(bytes), Ok(F::Png | F::Jpeg | F::Gif | F::WebP)) + use craft_image_codecs::Format as F; + matches!(craft_image_codecs::detect(bytes), Some(F::Png | F::Jpeg | F::Gif | F::WebP)) } /// `blob`, an image [`fileio::raster_image`] read from a file, ready to keep. When `unread` (the @@ -2455,12 +2455,30 @@ const UNEMBED_EXTS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "tif", "tif /// Encoded image `bytes` re-encoded in the format of extension `ext` (JPEG without alpha). fn convert_image(bytes: &[u8], ext: &str) -> std::result::Result, String> { - let format = image::ImageFormat::from_extension(ext).ok_or_else(|| format!("can't write .{ext} images"))?; - let img = image::load_from_memory(bytes).map_err(|e| e.to_string())?; - let img = if format == image::ImageFormat::Jpeg { image::DynamicImage::ImageRgb8(img.to_rgb8()) } else { img }; - let mut out = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut out), format).map_err(|e| e.to_string())?; - Ok(out) + let format = match ext.to_ascii_lowercase().as_str() { + "png" => craft_image_codecs::Format::Png, + "jpg" | "jpeg" => craft_image_codecs::Format::Jpeg, + "gif" => craft_image_codecs::Format::Gif, + "webp" => craft_image_codecs::Format::WebP, + "tif" | "tiff" => craft_image_codecs::Format::Tiff, + "bmp" => craft_image_codecs::Format::Bmp, + _ => return Err(format!("can't write .{ext} images")), + }; + let img = craft_image_codecs::decode(bytes).map_err(|e| e.to_string())?; + let raw = if format == craft_image_codecs::Format::Jpeg { + let rgb: Vec = img.to_rgba8().chunks_exact(4).flat_map(|p| [p[0], p[1], p[2]]).collect(); + craft_image_codecs::Image::from_raw( + img.width(), + img.height(), + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U8, + rgb, + ) + .map_err(|e| e.to_string())? + } else { + img + }; + craft_image_codecs::encode(&raw, format, &craft_image_codecs::EncodeOptions::default()).map_err(|e| e.to_string()) } fn unembed(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 1ab0e0b670..3617cbca7c 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -719,10 +719,16 @@ fn cmyk_raster( if alpha.iter().all(|&a| a == 255) { return Ok((blob, None)); } - let mask = image::GrayImage::from_raw(img.width, img.height, alpha) - .ok_or_else(|| EngineError::Other("the image's transparency doesn't fit it".into()))?; - let mut png = Vec::new(); - mask.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| EngineError::Other(e.to_string()))?; + let mask = craft_image_codecs::Image::from_raw( + img.width, + img.height, + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U8, + alpha, + ) + .map_err(|_| EngineError::Other("the image's transparency doesn't fit it".into()))?; + let png = craft_image_codecs::encode(&mask, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map_err(|e| EngineError::Other(e.to_string()))?; Ok((blob, Some(png))) } @@ -996,8 +1002,15 @@ fn crop_pixels(doc: &vectorcraft_doc::Document, im: &ImageObject, r: Rect) -> Op return None; } let cut = image::imageops::crop_imm(&px, x0, y0, x1 - x0, y1 - y0).to_image(); - let mut png = Vec::new(); - cut.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).ok()?; + let raw = craft_image_codecs::Image::from_raw( + cut.width(), + cut.height(), + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + cut.into_raw(), + ) + .ok()?; + let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; Some((png, x1 - x0, y1 - y0, im.xf * Affine::translate((f64::from(x0), f64::from(y0))))) } @@ -1088,22 +1101,15 @@ fn crop_image(s: &mut Session, p: &Value) -> Result { /// The image's pixels as RGBA, held to the allowance opening a raster has. fn decode_rgba(c: &str, blob: &vectorcraft_doc::ImageBlob) -> Result { // Print rasters run to gigabytes decoded: the same allowance opening them has. - let reader = || { - image::ImageReader::new(std::io::Cursor::new(blob.bytes.as_slice())) - .with_guessed_format() - .map_err(|_| bad(c, "the image's pixels can't be read")) - }; - // The image's size as RGBA, read from its header, is held to that allowance before anything - // is decoded (#1717). - let (w, h) = reader()?.into_dimensions().map_err(|e| bad(c, format!("the image's pixels can't be read: {e}")))?; - if u64::from(w) * u64::from(h) > crate::cmd::fileio::MAX_RASTER_ALLOC / 4 { - return Err(bad(c, format!("an image of {w} × {h} pixels is too large to draw"))); - } - let mut reader = reader()?; - let mut limits = image::Limits::default(); - limits.max_alloc = Some(crate::cmd::fileio::MAX_RASTER_ALLOC); - reader.limits(limits); - Ok(reader.decode().map_err(|e| bad(c, format!("the image's pixels can't be read: {e}")))?.to_rgba8()) + let mut opts = craft_image_codecs::DecodeOptions::default(); + opts.limits.max_pixels = crate::cmd::fileio::MAX_RASTER_ALLOC / 4; + opts.limits.max_alloc = crate::cmd::fileio::MAX_RASTER_ALLOC; + let img = craft_image_codecs::decode_with(&blob.bytes, &opts).map_err(|e| match e { + craft_image_codecs::CodecError::LimitExceeded(_) => bad(c, "the image is too large to draw"), + _ => bad(c, format!("the image's pixels can't be read: {e}")), + })?; + let (w, h) = img.dimensions(); + image::RgbaImage::from_raw(w, h, img.to_rgba8()).ok_or_else(|| bad(c, "the image's pixels can't be read")) } /// Crop Image's trim: the image cut to the box of its pixels that aren't fully transparent, the @@ -1132,9 +1138,12 @@ fn trim_image(s: &mut Session, id: NodeId, im: ImageObject) -> Result { return Ok(json!({ "id": id.0, "width": w, "height": h, "trimmed": false })); } let cut = image::imageops::crop_imm(&px, x0, y0, x1 - x0, y1 - y0).to_image(); - let mut png = Vec::new(); - cut.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| bad(C, e.to_string()))?; let (cw, ch) = (x1 - x0, y1 - y0); + let raw = + craft_image_codecs::Image::from_raw(cw, ch, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, cut.into_raw()) + .map_err(|e| bad(C, e.to_string()))?; + let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map_err(|e| bad(C, e.to_string()))?; put_pixels(s, id, png, cw, ch, im.xf * Affine::translate((f64::from(x0), f64::from(y0))))?; Ok(json!({ "id": id.0, "width": cw, "height": ch, "trimmed": true })) } diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index dc95f925b6..0418457056 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -888,15 +888,9 @@ fn queue(s: &mut Session, p: &Value) -> Result { /// The colour mode an image file stores its pixels in. fn color_mode(bytes: &[u8]) -> &'static str { - use image::{ExtendedColorType as E, ImageDecoder as _}; - let kind = image::ImageReader::new(std::io::Cursor::new(bytes)) - .with_guessed_format() - .ok() - .and_then(|r| r.into_decoder().ok()) - .map(|d| d.original_color_type()); - match kind { - Some(E::L1 | E::La1 | E::L2 | E::La2 | E::L4 | E::La4 | E::L8 | E::La8 | E::L16 | E::La16) => "Grayscale", - Some(E::Cmyk8 | E::Cmyk16) => "CMYK", + match craft_image_codecs::decode(bytes).ok().map(|img| img.layout()) { + Some(craft_image_codecs::ChannelLayout::Gray | craft_image_codecs::ChannelLayout::GrayA) => "Grayscale", + Some(craft_image_codecs::ChannelLayout::Cmyk | craft_image_codecs::ChannelLayout::CmykA) => "CMYK", _ => "RGB", } } diff --git a/crates/engine/src/cmd/place/document.rs b/crates/engine/src/cmd/place/document.rs index 8b00e95152..ac8390b1ba 100644 --- a/crates/engine/src/cmd/place/document.rs +++ b/crates/engine/src/cmd/place/document.rs @@ -295,17 +295,31 @@ fn preview(doc: &Document, art: &Node, frame: Rect) -> Option> { }) .collect(); let rgba = image::RgbaImage::from_raw(w, h, px)?; - let mut out = vec![]; - // Opaque but for the edge's anti-aliasing (an artboard drawn to whole pixels) and compositing's - // rounding: JPEG. let inner = |x: u32, y: u32| x > 0 && y > 0 && x + 1 < w && y + 1 < h; if rgba.enumerate_pixels().all(|(x, y, p)| p[3] >= 250 || !inner(x, y)) { let rgb = image::DynamicImage::ImageRgba8(rgba).to_rgb8(); - image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 80).encode_image(&rgb).ok()?; + let raw = craft_image_codecs::Image::from_raw( + rgb.width(), + rgb.height(), + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U8, + rgb.into_raw(), + ) + .ok()?; + let mut opts = craft_image_codecs::EncodeOptions::default(); + opts.jpeg_quality = 80; + craft_image_codecs::encode_with(&raw, craft_image_codecs::Format::Jpeg, &opts).ok() } else { - rgba.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).ok()?; + let raw = craft_image_codecs::Image::from_raw( + rgba.width(), + rgba.height(), + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + rgba.into_raw(), + ) + .ok()?; + craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok() } - Some(out) } /// `s` stored in `d` (objects showing the same thing share one blob). diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index 11c4744f47..372a297122 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -1934,7 +1934,41 @@ mod tests { /// A `size` px image of one color `rgba`. fn blob(rgba: [u8; 4], size: u32) -> ImageBlob { let mut png = Vec::new(); - image::RgbaImage::from_pixel(size, size, image::Rgba(rgba)).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(size, size, image::Rgba(rgba))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); ImageBlob::png(png) } @@ -1975,9 +2009,42 @@ mod tests { let d = Document::new(100.0, 100.0); let red = blob([255, 0, 0, 255], 64); let mut png = Vec::new(); - image::RgbaImage::from_fn(64, 64, |x, y| image::Rgba(if x >= 56 && y >= 56 { [0, 0, 255, 255] } else { [255, 0, 0, 255] })) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = + (image::RgbaImage::from_fn(64, 64, |x, y| image::Rgba(if x >= 56 && y >= 56 { [0, 0, 255, 255] } else { [255, 0, 0, 255] }))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let corner = ImageBlob::png(png); let mut t = Theme::new(&d); let whole = ImageRead { clip: None, ..clipped(&corner, 64.0, 4) }; diff --git a/crates/engine/src/cmd/webexport.rs b/crates/engine/src/cmd/webexport.rs index d1c66d9d3c..078391d5b7 100644 --- a/crates/engine/src/cmd/webexport.rs +++ b/crates/engine/src/cmd/webexport.rs @@ -782,9 +782,9 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8 /// An optimised image as straight RGBA → `(pixels, width, height)` (the dialog's preview). pub fn decode(o: &Optimized) -> std::result::Result<(Vec, u32, u32), String> { - let img = image::load_from_memory(o.display()).map_err(|e| format!("the optimised image can't be read back: {e}"))?.to_rgba8(); + let img = craft_image_codecs::decode(o.display()).map_err(|e| format!("the optimised image can't be read back: {e}"))?; let (w, h) = img.dimensions(); - Ok((img.into_raw(), w, h)) + Ok((img.to_rgba8(), w, h)) } /// Seconds to download `bytes` at `kbps` kilobits per second. diff --git a/crates/engine/src/tests/adjust.rs b/crates/engine/src/tests/adjust.rs index be4dd6a2d1..ea123961d1 100644 --- a/crates/engine/src/tests/adjust.rs +++ b/crates/engine/src/tests/adjust.rs @@ -31,7 +31,41 @@ pub(crate) fn fill_hex(n: &Node) -> String { fn red_image(s: &mut Session) -> NodeId { let img = image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, 255])); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); s.edit("Place", |d, sel| { d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(png)); let id = d.alloc_id(); @@ -108,13 +142,47 @@ fn an_embedded_image_is_adjusted_for_export_without_changing_its_pixels() { let baked = vectorcraft_render::effects::bake_document(&doc).unwrap(); let NodeKind::Image(im) = &baked.node(id).unwrap().kind else { panic!("not an image") }; assert_ne!(im.key, "pic", "a recoloured copy"); - let px = image::load_from_memory(&baked.images[&im.key].bytes).unwrap().to_rgba8(); + let px = craft_image_codecs::decode(&baked.images[&im.key].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!(px.get_pixel(1, 1).0, [0, 255, 0, 255]); assert_eq!(doc.images.len(), 1, "the document keeps its one image"); // Through Expand Appearance too. s.execute("effect.expandAppearance", &json!({})).unwrap(); let NodeKind::Image(im) = &node(&s, id).kind else { panic!("not an image") }; - let px = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8(); + let px = craft_image_codecs::decode(&s.doc().unwrap().doc.images[&im.key].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!(px.get_pixel(0, 0).0, [0, 255, 0, 255]); } diff --git a/crates/engine/src/tests/assets.rs b/crates/engine/src/tests/assets.rs index 8719873a94..57449bb9b6 100644 --- a/crates/engine/src/tests/assets.rs +++ b/crates/engine/src/tests/assets.rs @@ -140,7 +140,24 @@ fn an_asset_exports_its_art_alone() { run(&mut s, "assets.add", json!({"ids": [red]})); let out = files(&run(&mut s, "assets.export", json!({"formats": [{"format": "png", "scale": "2x"}]}))); assert_eq!(out[0].0, "Asset-1@2x.png"); - let img = image::load_from_memory(&out[0].1).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&out[0].1) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!(img.dimensions(), (40, 40)); assert!(img.pixels().all(|p| p.0 == [255, 0, 0, 255]), "only the red square"); // Vector formats crop to it too. @@ -163,7 +180,24 @@ fn an_assets_crop_takes_in_its_drop_shadow() { // The shadow's reach (10 pt) on every side. assert_eq!(assets(&mut s)[0]["bounds"], json!([40.0, 40.0, 40.0, 40.0])); let out = files(&run(&mut s, "assets.export", json!({"formats": [{"format": "png", "scale": "1x"}]}))); - let img = image::load_from_memory(&out[0].1).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&out[0].1) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!(img.dimensions(), (40, 40)); // The shadow's right half, x 70 to 80. assert!(img.get_pixel(35, 20)[3] > 0, "the shadow is in the image"); @@ -381,7 +415,29 @@ fn export_for_screens_writes_chosen_assets_and_keeps_its_rules() { let out = files(&r); assert_eq!(out.len(), 1); assert_eq!(out[0].0, "Asset-2@60w.png"); - assert_eq!(image::load_from_memory(&out[0].1).unwrap().to_rgba8().dimensions(), (60, 40), "the width of the asset, not the artboard"); + assert_eq!( + craft_image_codecs::decode(&out[0].1) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() + .dimensions(), + (60, 40), + "the width of the asset, not the artboard" + ); // The choice of art isn't remembered; the formats are. let settings = run(&mut s, "document.exportSettings", json!({}))["settings"].clone(); assert!(settings.get("assets").is_none() && settings["formats"][0]["scale"] == "60w"); @@ -430,7 +486,24 @@ fn assets_export_leaves_no_seam_between_abutting_shapes() { }), )); assert_eq!(out[0].0, "Asset-1.png"); - let img = image::load_from_memory(&out[0].1).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&out[0].1) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!(img.dimensions(), (40, 20)); // Column 20 is the shared edge in crop space; green must stay red (no white bleed). let palest_g = (2..18).map(|y| img.get_pixel(20, y).0[1].max(img.get_pixel(19, y).0[1])).max().unwrap(); diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 01eb7f7132..4cef5c5cea 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -3830,7 +3830,41 @@ fn live_paint_bucket_alt_image_samples_fill_and_clears_stroke() { let mut s = session(); let img = image::RgbaImage::from_raw(1, 1, vec![0, 255, 0, 255]).unwrap(); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); s.edit("Place", |d, _| { d.images.insert("px".into(), ImageBlob::png(png)); let id = d.alloc_id(); diff --git a/crates/engine/src/tests/clipflavours.rs b/crates/engine/src/tests/clipflavours.rs index 5955389aea..ba1dfbf75f 100644 --- a/crates/engine/src/tests/clipflavours.rs +++ b/crates/engine/src/tests/clipflavours.rs @@ -59,7 +59,24 @@ fn exported_png_of_a_red_square_is_red() { copy_red_square(&mut s); let r = run(&mut s, "clipboard.exportPng", json!({"scale": 2})); assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(80), Some(80))); - let img = image::load_from_memory(&decode(&r)).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&decode(&r)) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!(img.dimensions(), (80, 80)); assert_eq!(img.get_pixel(40, 40).0, [255, 0, 0, 255]); assert_eq!(img.get_pixel(2, 77).0, [255, 0, 0, 255], "cropped to the square"); @@ -155,7 +172,41 @@ fn import_image_then_paste_gives_an_image() { #[test] fn an_image_read_apart_loads_as_import_image_loads_it() { let mut bmp = vec![]; - image::RgbImage::from_pixel(30, 20, image::Rgb([200, 40, 40])).write_to(&mut std::io::Cursor::new(&mut bmp), image::ImageFormat::Bmp).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbImage::from_pixel(30, 20, image::Rgb([200, 40, 40]))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Bmp, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| bmp.extend_from_slice(&__b)) + } + .unwrap(); let (mut at_once, mut apart) = (session(), session()); let p = json!({"mime": "image/bmp", "center": [100, 80]}); let mut with_data = p.clone(); @@ -195,7 +246,41 @@ fn a_pasted_bitmap_is_drawn_without_decoding_it_again() { // The image has pixels no other test uses, since every test shares the image store. let img = image::RgbImage::from_fn(300, 200, |x, y| image::Rgb([(x % 253) as u8, (y % 233) as u8, 17])); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let mut s = session(); run(&mut s, "clipboard.importImage", json!({"dataBase64": vectorcraft_format::base64_encode(&png), "mime": "image/png"})); run(&mut s, "edit.paste", json!({})); @@ -278,7 +363,41 @@ fn copied_files_paste_by_their_content() { let png = decode(&run(&mut s, "clipboard.exportPng", json!({}))); let pdf = decode(&run(&mut s, "clipboard.exportPdf", json!({}))); let mut jpeg = vec![]; - image::RgbImage::new(2, 2).write_to(&mut std::io::Cursor::new(&mut jpeg), image::ImageFormat::Jpeg).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbImage::new(2, 2)).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Jpeg, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| jpeg.extend_from_slice(&__b)) + } + .unwrap(); let svg = b""; let of = |name: &str, bytes: &[u8]| file_flavour(name, &bytes[..bytes.len().min(FILE_HEAD)], &PASTE_ORDER); assert_eq!(of("red.png", &png), Some(PNG)); @@ -402,7 +521,23 @@ fn copy_leaves_out_the_png_of_art_too_large_to_scale_down() { run(&mut s, "select.set", json!({"ids": [id]})); run(&mut s, "edit.copy", json!({})); let png = s.clipboard.flavours(false, false).into_iter().find(|f| f.mime == PNG).expect("a PNG"); - let img = image::load_from_memory(&png.data).unwrap(); + let img = craft_image_codecs::decode(&png.data) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap(); assert!(img.width() <= 4096 && img.height() <= 4096, "{}x{}", img.width(), img.height()); } @@ -445,7 +580,41 @@ fn noise_png(side: u32) -> Vec { }) .collect(); let mut out = vec![]; - image::RgbImage::from_raw(side, side, px).unwrap().write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbImage::from_raw(side, side, px).unwrap()).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); out } diff --git a/crates/engine/src/tests/colorize.rs b/crates/engine/src/tests/colorize.rs index e281b3ee04..3425ab526d 100644 --- a/crates/engine/src/tests/colorize.rs +++ b/crates/engine/src/tests/colorize.rs @@ -15,7 +15,41 @@ fn session() -> Session { fn png(img: image::DynamicImage) -> ImageBlob { let mut out = Vec::new(); - img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); ImageBlob::png(out) } diff --git a/crates/engine/src/tests/containers.rs b/crates/engine/src/tests/containers.rs index 42cebea2ad..5a5de63172 100644 --- a/crates/engine/src/tests/containers.rs +++ b/crates/engine/src/tests/containers.rs @@ -186,9 +186,41 @@ fn type_with_an_inline_graphic_stays_type_when_its_own_stroke_has_an_effect() { /// A selected 30×30 red image placed with its frame from (50, 50) to (80, 80). fn image(s: &mut Session) -> NodeId { let mut png = vec![]; - image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255]))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let r = run(s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [65, 65]})); NodeId(r["ids"][0].as_u64().unwrap()) } @@ -259,11 +291,44 @@ fn an_images_stroke_with_outline_object_draws_exports_and_expands_along_its_fram /// A 100×100 PNG, transparent but for an opaque red disc of radius 30 in its middle. fn disc_png() -> Vec { let mut png = vec![]; - image::RgbaImage::from_fn(100, 100, |x, y| { - let r = (f64::from(x) + 0.5 - 50.0).hypot(f64::from(y) + 0.5 - 50.0); - image::Rgba([255, 0, 0, if r <= 30.0 { 255 } else { 0 }]) - }) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_fn(100, 100, |x, y| { + let r = (f64::from(x) + 0.5 - 50.0).hypot(f64::from(y) + 0.5 - 50.0); + image::Rgba([255, 0, 0, if r <= 30.0 { 255 } else { 0 }]) + })) + .into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } .unwrap(); png } @@ -316,9 +381,41 @@ fn an_images_stroke_with_outline_object_follows_its_opaque_area() { std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("opaque.png"); let mut png = vec![]; - image::RgbaImage::from_pixel(100, 100, image::Rgba([255, 0, 0, 255])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(100, 100, image::Rgba([255, 0, 0, 255]))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); std::fs::write(&path, png).unwrap(); run(&mut s, "links.relink", json!({"ids": [im.0], "path": path})); assert_eq!([shade(&s, 41, 100), shade(&s, 45, 100), shade(&s, 64, 100)], ["white", "black", "red"]); diff --git a/crates/engine/src/tests/dynamic_symbols.rs b/crates/engine/src/tests/dynamic_symbols.rs index c5ef8a1949..1cbcd673d9 100644 --- a/crates/engine/src/tests/dynamic_symbols.rs +++ b/crates/engine/src/tests/dynamic_symbols.rs @@ -798,7 +798,41 @@ fn a_blend_around_a_picked_objects_instance_is_left_alone() { fn image_symbol(s: &mut Session) -> (NodeId, Value) { let mut png = Vec::new(); let pixels = image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap()); - pixels.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (pixels).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let im = s .edit("Place", |d, _| { d.images.insert("gray".into(), vectorcraft_doc::ImageBlob::png(png)); diff --git a/crates/engine/src/tests/editcolors.rs b/crates/engine/src/tests/editcolors.rs index a1abfeb259..a2d2e85e48 100644 --- a/crates/engine/src/tests/editcolors.rs +++ b/crates/engine/src/tests/editcolors.rs @@ -403,14 +403,68 @@ fn blend_moves_a_mesh_to_the_blended_colour() { fn png(px: [[u8; 4]; 4]) -> Vec { let img = image::RgbaImage::from_raw(2, 2, px.concat()).unwrap(); let mut out = Vec::new(); - img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); out } fn pixels(s: &Session, id: NodeId) -> Vec<[u8; 4]> { let d = &s.doc().unwrap().doc; let NodeKind::Image(im) = &d.node(id).unwrap().kind else { panic!("not an image") }; - image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect() + craft_image_codecs::decode(&d.images[&im.key].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() + .pixels() + .map(|p| p.0) + .collect() } /// A selected embedded 2×2 image. @@ -652,7 +706,41 @@ fn convert_to_indexed_refuses_bad_params() { /// An embedded `w` × `h` image of the pixels `f(x, y)`, placed and selected. fn placed(s: &mut Session, w: u32, h: u32, f: impl Fn(u32, u32) -> [u8; 4]) -> NodeId { let mut png = Vec::new(); - image::RgbaImage::from_fn(w, h, |x, y| image::Rgba(f(x, y))).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_fn(w, h, |x, y| image::Rgba(f(x, y)))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let r = s.execute("file.place", &json!({"name": "art.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); NodeId(r["ids"][0].as_u64().unwrap()) } @@ -681,7 +769,41 @@ fn convert_to_indexed_takes_ids_and_leaves_linked_and_colorized_images() { assert_eq!(image_key(&s, a), ka); assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step"); let mut png = Vec::new(); - image::GrayImage::from_pixel(4, 4, image::Luma([90])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::GrayImage::from_pixel(4, 4, image::Luma([90]))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let r = s.execute("file.place", &json!({"name": "gray.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); let gray = NodeId(r["ids"][0].as_u64().unwrap()); s.execute("paint.setFill", &json!({"ids": [gray.0], "color": "#ff0000"})).unwrap(); diff --git a/crates/engine/src/tests/envelope_distort.rs b/crates/engine/src/tests/envelope_distort.rs index a0193a27f8..0a4be6e3ce 100644 --- a/crates/engine/src/tests/envelope_distort.rs +++ b/crates/engine/src/tests/envelope_distort.rs @@ -117,7 +117,41 @@ fn the_frame_round_trips_natively() { fn red_image(s: &mut Session) -> NodeId { let img = image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, 255])); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); s.edit("Place", |d, sel| { d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(png)); let id = d.alloc_id(); @@ -159,7 +193,41 @@ fn a_colorized_image_keeps_its_color_in_an_envelope() { let mut s = session(); let img = image::GrayImage::from_pixel(4, 4, image::Luma([0])); let mut png = vec![]; - image::DynamicImage::ImageLuma8(img).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::DynamicImage::ImageLuma8(img)).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let im = s .edit("Place", |d, sel| { d.images.insert("gray".into(), vectorcraft_doc::ImageBlob::png(png)); @@ -187,7 +255,41 @@ fn a_colorized_image_keeps_its_color_in_an_envelope() { fn two_color_image(s: &mut Session) -> NodeId { let img = image::RgbaImage::from_fn(2, 2, |x, _| if x == 0 { image::Rgba([255, 0, 0, 255]) } else { image::Rgba([0, 0, 255, 255]) }); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); s.edit("Place", |d, sel| { d.images.insert("two".into(), vectorcraft_doc::ImageBlob::png(png)); let id = d.alloc_id(); diff --git a/crates/engine/src/tests/eyedropper.rs b/crates/engine/src/tests/eyedropper.rs index b3a9012e06..0079d062bf 100644 --- a/crates/engine/src/tests/eyedropper.rs +++ b/crates/engine/src/tests/eyedropper.rs @@ -562,7 +562,41 @@ fn clicking_an_image_samples_its_pixel() { // Two pixels, orange and teal, 100 pt each, at (300, 0). let img = image::RgbaImage::from_raw(2, 1, [[255, 128, 0, 255], [0, 128, 128, 255]].concat()).unwrap(); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); s.edit("Place", |d, _| { d.images.insert("px".into(), ImageBlob::png(png)); let l = d.layers[0].id; @@ -588,7 +622,41 @@ fn cmyk_doc_with_image(px: &[[u8; 4]]) -> Session { let w = px.len() as u32; let img = image::RgbaImage::from_raw(w, 1, px.concat()).unwrap(); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); s.edit("Place", |d, _| { d.images.insert("px".into(), ImageBlob::png(png)); let l = d.layers[0].id; diff --git a/crates/engine/src/tests/file.rs b/crates/engine/src/tests/file.rs index b3b041e2e2..b2cbefee3d 100644 --- a/crates/engine/src/tests/file.rs +++ b/crates/engine/src/tests/file.rs @@ -459,7 +459,24 @@ fn export_selection_keeps_the_effects_in_the_crop() { assert_eq!(plain["bounds"], json!([99.5, 99.5, 21.0, 21.0]), "a plain path keeps its crop: {plain}"); s.execute("effect.apply", &json!({"effect": effect, "params": params})).unwrap(); let png = |v: &serde_json::Value| { - image::load_from_memory(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()).unwrap().to_rgba8() + craft_image_codecs::decode(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() }; let v = s.execute("document.exportSelection", &json!({"format": "png", "background": "transparent"})).unwrap(); let b: Vec = v["bounds"].as_array().unwrap().iter().map(|n| n.as_f64().unwrap()).collect(); @@ -485,7 +502,24 @@ fn a_screen_outer_glow_is_in_raster_exports() { s.execute("effect.apply", &json!({"effect": "stylize.outerGlow"})).unwrap(); let mut pixel = |p: serde_json::Value| { let v = s.execute("document.export", &p).unwrap(); - let img = image::load_from_memory(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); // 2 pt past the square's stroke, on the right. *img.get_pixel(122, 110) }; @@ -512,7 +546,24 @@ fn export_selection_keeps_a_groups_shadow_in_the_crop() { let b: Vec = v["bounds"].as_array().unwrap().iter().map(|n| n.as_f64().unwrap()).collect(); // The shadow of the right square reaches x = 158.5. assert!(b[0] < 99.5 && b[0] + b[2] >= 158.5, "{v}"); - let img = image::load_from_memory(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert!(img.get_pixel((155.0 - b[0]) as u32, img.height() / 2)[3] > 0, "the shadow is in the image"); } @@ -534,7 +585,24 @@ fn the_arts_bounds_take_in_the_shadow_of_a_group_and_of_type() { s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [id], "params": {"x": 8, "y": 0, "blur": 0}})).unwrap(); s.execute("select.set", &json!({"ids": [id]})).unwrap(); let png = |v: &serde_json::Value| { - image::load_from_memory(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()).unwrap().to_rgba8() + craft_image_codecs::decode(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() }; let art = s.execute("document.export", &json!({"format": "png", "useArtboards": false, "background": "transparent"})).unwrap(); let sel = s.execute("document.exportSelection", &json!({"format": "png", "background": "transparent"})).unwrap(); diff --git a/crates/engine/src/tests/fileinfo.rs b/crates/engine/src/tests/fileinfo.rs index 4d86a84b3c..ec45e94259 100644 --- a/crates/engine/src/tests/fileinfo.rs +++ b/crates/engine/src/tests/fileinfo.rs @@ -476,7 +476,26 @@ fn png_exports_carry_text_chunks() { assert_eq!(get("Keywords"), Some("fair, Poster, print")); assert_eq!(get("Copyright"), Some("(c) 2026 Ada")); assert!(get("Creation Time").is_some_and(|t| t.ends_with('Z'))); - assert!(image::load_from_memory(&png).is_ok(), "still a valid PNG"); + assert!( + craft_image_codecs::decode(&png) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .is_ok(), + "still a valid PNG" + ); } #[test] diff --git a/crates/engine/src/tests/legacy_ai.rs b/crates/engine/src/tests/legacy_ai.rs index fefed0ad11..df12becc1e 100644 --- a/crates/engine/src/tests/legacy_ai.rs +++ b/crates/engine/src/tests/legacy_ai.rs @@ -300,7 +300,41 @@ fn a_radial_gradient_lists_its_stops_from_the_first() { /// A `w`×`h` PNG of one colour (`rgba`), 72 ppi. fn png(w: u32, h: u32, rgba: [u8; 4]) -> Vec { let mut out = vec![]; - image::RgbaImage::from_pixel(w, h, image::Rgba(rgba)).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(w, h, image::Rgba(rgba))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); out } @@ -402,7 +436,41 @@ fn disk(size: u32, r: f64) -> Vec { image::Rgba([0, 0, 0, ((r + 0.5 - d).clamp(0.0, 1.0) * 255.0).round() as u8]) }); let mut out = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); out } @@ -530,7 +598,41 @@ fn colorized_bitmap_over_square() -> (Session, Vec) { s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); let gray = vec![0, 255, 0, 255, 255, 0, 255, 0]; let mut bytes = vec![]; - image::GrayImage::from_raw(4, 2, gray.clone()).unwrap().write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::GrayImage::from_raw(4, 2, gray.clone()).unwrap()).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| bytes.extend_from_slice(&__b)) + } + .unwrap(); let p = json!({"name": "b.png", "dataBase64": vectorcraft_format::base64_encode(&bytes), "rect": [30, 10, 40, 20]}); s.execute("file.place", &p).unwrap(); s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap(); @@ -593,10 +695,41 @@ fn a_colorized_image_of_black_and_clear_pixels_is_written_as_an_image_mask() { s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); s.execute("swatch.new", &json!({"name": "Ink", "color": {"c": 100, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap(); let mut bytes = vec![]; - image::GrayAlphaImage::from_raw(2, 1, vec![0, 255, 0, 0]) - .unwrap() - .write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::GrayAlphaImage::from_raw(2, 1, vec![0, 255, 0, 0]).unwrap()).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| bytes.extend_from_slice(&__b)) + } + .unwrap(); let p = json!({"name": "c.png", "dataBase64": vectorcraft_format::base64_encode(&bytes), "rect": [30, 10, 20, 10]}); s.execute("file.place", &p).unwrap(); s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap(); @@ -732,7 +865,41 @@ fn an_artboard_the_document_does_not_have_is_refused_as_an_export_refuses_it() { fn checker(a: [u8; 4], b: [u8; 4]) -> Vec { let img = image::RgbaImage::from_fn(32, 32, |x, y| image::Rgba(if (x < 16) == (y < 16) { a } else { b })); let mut out = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); out } @@ -760,7 +927,41 @@ fn colorized_pattern_over_blue() -> Session { let tile = image::GrayImage::from_fn(32, 32, |x, y| image::Luma([if (x < 16) == (y < 16) { 0 } else { 255 }])); let mut bytes = vec![]; - tile.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (tile).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| bytes.extend_from_slice(&__b)) + } + .unwrap(); let mut s = pattern_over_blue(&bytes, 1.0); let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); assert!(d.patterns[0].art.iter_mut().any(|art| colorize_image(std::sync::Arc::make_mut(art)))); diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs index 62d3e36bad..833853ce98 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -35,7 +35,41 @@ impl Drop for Folder { pub(crate) fn png(w: u32, h: u32, rgb: [u8; 3]) -> Vec { let mut out = vec![]; let [r, g, b] = rgb; - image::RgbaImage::from_pixel(w, h, image::Rgba([r, g, b, 255])).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(w, h, image::Rgba([r, g, b, 255]))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); out } @@ -200,7 +234,41 @@ fn linked_dib_and_pns_files_place_update_and_relink() { let bmp = |w: u32, h: u32, rgb: [u8; 3]| { let mut out = vec![]; let [r, g, b] = rgb; - image::RgbImage::from_pixel(w, h, image::Rgb([r, g, b])).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Bmp).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbImage::from_pixel(w, h, image::Rgb([r, g, b]))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Bmp, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); out }; let dir = Folder::new("dib"); @@ -1300,7 +1368,41 @@ pub(crate) fn cut_png(w: u32, h: u32) -> Vec { image::Rgb([v as u8, (v >> 8) as u8, (v >> 16) as u8]) }); let mut out = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); out.truncate(out.len() / 2); out } @@ -1414,12 +1516,27 @@ fn low_res_proxy_eps_export_uses_full_resolution_from_the_linked_file() { let (full, warnings) = cmd::links::full_linked_images(&s.doc().unwrap().doc, Default::default()); assert!(warnings.is_empty(), "{warnings:?}"); assert!(!full.images[&key].is_proxy()); - let dim = - image::ImageReader::new(std::io::Cursor::new(full.images[&key].bytes.as_ref())).with_guessed_format().unwrap().into_dimensions().unwrap(); + let dim = craft_image_codecs::decode(full.images[&key].bytes.as_ref()).unwrap().dimensions(); assert_eq!(dim, (600, 300)); let png_out = s.execute("document.export", &json!({"format": "png"})).unwrap(); let bytes = vectorcraft_format::base64_decode(png_out["dataBase64"].as_str().unwrap()).unwrap(); - let rendered = image::load_from_memory(&bytes).unwrap(); + let rendered = craft_image_codecs::decode(&bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap(); assert!(rendered.width() >= 400 && rendered.height() >= 300); assert!(near(centre_colour(&s.doc().unwrap().doc), RED), "canvas still shows the preview"); } @@ -1489,7 +1606,41 @@ fn a_file_read_for_opening_has_its_links_read_and_its_type_laid_out() { let dir = Folder::new("read-for-open"); let tif = dir.file("art/photo.tif"); let mut tiff = vec![]; - image::RgbImage::from_pixel(600, 300, image::Rgb(RED)).write_to(&mut std::io::Cursor::new(&mut tiff), image::ImageFormat::Tiff).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbImage::from_pixel(600, 300, image::Rgb(RED))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Tiff, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| tiff.extend_from_slice(&__b)) + } + .unwrap(); write(&tif, &tiff); let (gone, changed) = (dir.file("gone.png"), dir.file("changed.png")); write(&gone, &png(300, 100, BLUE)); diff --git a/crates/engine/src/tests/live.rs b/crates/engine/src/tests/live.rs index c372bcf784..f2723ca825 100644 --- a/crates/engine/src/tests/live.rs +++ b/crates/engine/src/tests/live.rs @@ -1525,7 +1525,41 @@ fn two_colour_image(s: &mut Session, clear_right: bool, linked: bool) -> NodeId let right = image::Rgba([0, 0, 255, if clear_right { 0 } else { 255 }]); let img = image::RgbaImage::from_fn(8, 4, |x, _| if x < 4 { image::Rgba([255, 0, 0, 255]) } else { right }); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); s.edit("Place", |d, sel| { d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(png)); let id = d.alloc_id(); diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index abb0bf31eb..a53bdcbb32 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -48,9 +48,41 @@ pub(crate) fn place_undecodable_png(s: &mut Session) -> NodeId { /// different images, each stored under its own key. pub(crate) fn place_undecodable_png_sized(s: &mut Session, w: u32, h: u32) -> NodeId { let mut png = Vec::new(); - image::RgbaImage::from_pixel(w, h, image::Rgba([200, 30, 30, 255])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(w, h, image::Rgba([200, 30, 30, 255]))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let r = s.execute("file.place", &json!({"name": "cut.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); let id = NodeId(r["ids"][0].as_u64().unwrap()); cut_pixels(s, id); @@ -1557,7 +1589,41 @@ fn busy_image_at_two_points_a_pixel() -> (Session, NodeId, image::RgbaImage) { *p = image::Rgba([(x * 37 % 256) as u8, (y * 91 % 256) as u8, ((x ^ y) * 13 % 256) as u8, 255]); } let mut png = Vec::new(); - px.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (px).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let mut s = Session::new(); s.execute("document.open", &json!({"name": "art.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); s.execute("select.all", &json!({})).unwrap(); @@ -1575,7 +1641,24 @@ fn crop_image_to_rect_copies_the_pixels_without_resampling() { let b = bounds(&s, img); assert!(close(b.x0, 20.0) && close(b.y0, 10.0) && close(b.width(), 60.0) && close(b.height(), 40.0), "{b:?}"); let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") }; - let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8(); + let out = craft_image_codecs::decode(&s.doc().unwrap().doc.images[&im.key].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!(out, image::imageops::crop_imm(&px, 10, 5, 30, 20).to_image()); } @@ -5023,7 +5106,41 @@ fn crop_image_trim_cuts_to_the_opaque_pixels_as_they_are() { } } let mut png = Vec::new(); - px.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (px).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let mut s = Session::new(); s.execute("document.open", &json!({"name": "art.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); s.execute("select.all", &json!({})).unwrap(); @@ -5036,7 +5153,24 @@ fn crop_image_trim_cuts_to_the_opaque_pixels_as_they_are() { assert!(close(b.x0, 40.0) && close(b.y0, 20.0) && close(b.width(), 60.0) && close(b.height(), 60.0), "{b:?}"); // Pixel for pixel, a barely visible (alpha 1) edge included. let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") }; - let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8(); + let out = craft_image_codecs::decode(&s.doc().unwrap().doc.images[&im.key].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!(out, image::imageops::crop_imm(&px, 20, 10, 30, 30).to_image()); assert_eq!(r["trimmed"], true); // Nothing transparent left to cut: left as it is, and not an error (scripts trim every image). diff --git a/crates/engine/src/tests/nativefile.rs b/crates/engine/src/tests/nativefile.rs index 4156dc7599..336c14dcea 100644 --- a/crates/engine/src/tests/nativefile.rs +++ b/crates/engine/src/tests/nativefile.rs @@ -126,7 +126,23 @@ fn preview_is_at_most_256_pixels() { let mut s = session(); let bytes = saved(&mut s, json!({"preview": true, "compress": true})); let png = vectorcraft_format::preview(&bytes).expect("a preview"); - let img = image::load_from_memory(&png).unwrap(); + let img = craft_image_codecs::decode(&png) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap(); assert_eq!((img.width(), img.height()), (256, 128), "the 400×200 artboard fitted into 256 px"); assert!(vectorcraft_format::preview(&saved(&mut s, json!({}))).is_none(), "off by default"); } @@ -154,7 +170,41 @@ fn saving_writes_through_a_temporary_file() { fn unused_images_are_left_out_of_saves() { let mut s = session(); let mut png = vec![]; - image::RgbaImage::from_pixel(4, 4, image::Rgba([1, 2, 3, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(4, 4, image::Rgba([1, 2, 3, 255]))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let r = s.execute("file.place", &json!({"name": "a.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); let id = r["ids"][0].as_u64().unwrap(); assert_eq!(json_of(&saved(&mut s, json!({})))["images"].as_object().unwrap().len(), 1); diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index 094f634799..9e20de0ad1 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -90,7 +90,26 @@ fn a_white_background_exports_opaque() { let mut s = new_doc(json!({"width": 20, "height": 20, "backgroundContents": bg})); let r = s.execute("document.export", &json!({"format": "png"})).unwrap(); let png = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); - image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(10, 10).0 + craft_image_codecs::decode(&png) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() + .get_pixel(10, 10) + .0 }; assert_eq!(alpha("white"), [255, 255, 255, 255]); assert_eq!(alpha("transparent")[3], 0); @@ -540,9 +559,41 @@ fn edit_print_profile(s: &mut Session, dir: &std::path::Path) { // One embedded image becomes a symbol's art, another stays on the profile's layer. let png = |rgb: [u8; 3]| { let mut out = vec![]; - image::RgbaImage::from_pixel(4, 4, image::Rgba([rgb[0], rgb[1], rgb[2], 255])) - .write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(4, 4, image::Rgba([rgb[0], rgb[1], rgb[2], 255]))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); vectorcraft_format::base64_encode(&out) }; s.execute("file.place", &json!({"name": "red.png", "dataBase64": png([255, 0, 0]), "link": false})).unwrap(); diff --git a/crates/engine/src/tests/pdfraster.rs b/crates/engine/src/tests/pdfraster.rs index 1e0a2ecfde..b9eecd7fbd 100644 --- a/crates/engine/src/tests/pdfraster.rs +++ b/crates/engine/src/tests/pdfraster.rs @@ -38,7 +38,41 @@ fn with(mut n: Node, fx: Effect) -> Node { fn png(w: u32, h: u32) -> Vec { let img = image::RgbaImage::from_fn(w, h, |x, _| image::Rgba([(x * 255 / w) as u8, 60, 160, 255])); let mut out = Vec::new(); - image::DynamicImage::from(img).write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::DynamicImage::from(img)).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); out } diff --git a/crates/engine/src/tests/place.rs b/crates/engine/src/tests/place.rs index 8dbe06f349..93c98e275b 100644 --- a/crates/engine/src/tests/place.rs +++ b/crates/engine/src/tests/place.rs @@ -20,7 +20,41 @@ fn session() -> Session { /// A `w`×`h` PNG of one colour (`rgba`), declaring `ppi` when given. fn png(w: u32, h: u32, rgba: [u8; 4], ppi: Option) -> Vec { let mut out = vec![]; - image::RgbaImage::from_pixel(w, h, image::Rgba(rgba)).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(w, h, image::Rgba(rgba))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); match ppi { Some(r) => cmd::fileio::ppi::with_png_resolution(&out, (r, r)), None => out, @@ -482,13 +516,46 @@ fn keeping_an_image_decodes_nothing() { } /// `w`×`h` pixels of noise, which compress little, encoded as `format`. -fn noise(w: u32, h: u32, format: image::ImageFormat) -> Vec { +fn noise(w: u32, h: u32, format: craft_image_codecs::Format) -> Vec { let img = image::RgbImage::from_fn(w, h, |x, y| { let v = x.wrapping_mul(2_654_435_761) ^ y.wrapping_mul(40_503).rotate_left(13); image::Rgb([v as u8, (v >> 8) as u8, (v >> 16) as u8]) }); let mut out = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut out), format).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, format, &craft_image_codecs::EncodeOptions::default()).map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); out } @@ -497,7 +564,7 @@ fn noise(w: u32, h: u32, format: image::ImageFormat) -> Vec { /// cut short still decodes, with its missing rows empty, and is placed. #[test] fn an_image_whose_pixels_cant_be_read_is_not_placed() { - let mut cut = noise(600, 300, image::ImageFormat::Png); + let mut cut = noise(600, 300, craft_image_codecs::Format::Png); cut.truncate(cut.len() / 2); let mut s = session(); let info = s.execute("file.place.info", &file("cut.png", &cut)).unwrap(); @@ -513,7 +580,7 @@ fn an_image_whose_pixels_cant_be_read_is_not_placed() { assert!(top_children(&s).is_empty(), "{p}: nothing placed"); assert_eq!((s.doc().unwrap().history.undo.len(), s.journal.len()), (undo, journal), "{p}"); } - let mut jpeg = noise(600, 300, image::ImageFormat::Jpeg); + let mut jpeg = noise(600, 300, craft_image_codecs::Format::Jpeg); jpeg.truncate(jpeg.len() / 2); let r = place(&mut s, "cut.jpg", &jpeg, json!({})); assert_eq!(r["format"], "jpg"); @@ -894,7 +961,41 @@ fn placed_art_brings_its_brushes_renaming_on_conflict() { fn a_placed_brush_whose_art_uses_a_renamed_image_is_copied() { let file = |pixel: u8| { let mut png = vec![]; - image::GrayImage::from_pixel(2, 1, image::Luma([pixel])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::GrayImage::from_pixel(2, 1, image::Luma([pixel]))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let mut s = session(); s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); s.edit("Brush", |d, _| { @@ -942,7 +1043,41 @@ fn a_placed_brush_whose_art_uses_a_renamed_image_is_copied() { fn info_reports_size_resolution_colour_mode_and_link() { let mut s = session(); let mut gray = vec![]; - image::GrayImage::from_pixel(300, 150, image::Luma([128])).write_to(&mut std::io::Cursor::new(&mut gray), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::GrayImage::from_pixel(300, 150, image::Luma([128]))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| gray.extend_from_slice(&__b)) + } + .unwrap(); let gray = cmd::fileio::ppi::with_png_resolution(&gray, (300.0, 300.0)); let mut p = file("scan.png", &gray); p["thumbnail"] = json!(16); @@ -950,7 +1085,23 @@ fn info_reports_size_resolution_colour_mode_and_link() { assert_eq!((info["colorMode"].as_str(), info["pixelWidth"].as_u64()), (Some("Grayscale"), Some(300))); assert_eq!(info["ppi"], json!([300.0, 300.0])); assert!(close(info["width"].as_f64().unwrap(), 72.0)); - let thumb = image::load_from_memory(&vectorcraft_format::base64_decode(info["thumbnailBase64"].as_str().unwrap()).unwrap()).unwrap(); + let thumb = craft_image_codecs::decode(&vectorcraft_format::base64_decode(info["thumbnailBase64"].as_str().unwrap()).unwrap()) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap(); assert_eq!((thumb.width(), thumb.height()), (16, 8)); assert!(top_children(&s).is_empty(), "info places nothing"); // A path is linked by default. @@ -1090,7 +1241,7 @@ fn files_read_for_the_place_cursor_apart_from_the_session_load_it_as_file_place_ /// queue, read with the session or apart from it. #[test] fn the_place_queue_skips_an_image_whose_pixels_cant_be_read() { - let mut cut = noise(600, 300, image::ImageFormat::Png); + let mut cut = noise(600, 300, craft_image_codecs::Format::Png); cut.truncate(cut.len() / 2); let p = json!({"files": [file("a.png", &png(40, 20, [9, 9, 9, 255], None)), file("cut.png", &cut)], "link": false}); let (mut a, mut b) = (session(), session()); @@ -1108,7 +1259,41 @@ fn the_place_queue_draws_a_thumbnail_without_decoding_the_image_again() { // Pixels no other test uses, since every test shares the image store. let img = image::RgbImage::from_fn(320, 160, |x, y| image::Rgb([(x % 251) as u8, 23, (y % 241) as u8])); let mut bytes = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| bytes.extend_from_slice(&__b)) + } + .unwrap(); let p = json!({"files": [file("q.png", &bytes)], "link": false, "thumbnail": 64}); let decodes = vectorcraft_render::image_decodes(); let r = session().execute("file.place.queue", &p).unwrap(); diff --git a/crates/engine/src/tests/placed_document.rs b/crates/engine/src/tests/placed_document.rs index c639fc9232..024f1bcf22 100644 --- a/crates/engine/src/tests/placed_document.rs +++ b/crates/engine/src/tests/placed_document.rs @@ -152,7 +152,26 @@ fn a_placed_document_is_vectors_in_every_output() { assert_eq!(images, 0, "no image in the PDF"); assert!(paths > 0); let png = decode(&s.execute("document.serialize", &json!({"format": "png"})).unwrap()); - let [r, g, b, _] = image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(200, 150).0; + let [r, g, b, _] = craft_image_codecs::decode(&png) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() + .get_pixel(200, 150) + .0; assert!(near([r, g, b], RED), "{:?}", [r, g, b]); for format in ["eps", "emf", "dxf"] { let out = s.execute("document.serialize", &json!({"format": format})).unwrap(); @@ -192,7 +211,26 @@ fn the_preview_is_saved_so_the_document_shows_it_without_its_file() { // Output with the file gone: the preview, with a warning. let png = s.execute("document.serialize", &json!({"format": "png"})).unwrap(); assert!(png["warnings"].to_string().contains("1 placed document output as its preview"), "{png}"); - let [r, g, b, _] = image::load_from_memory(&decode(&png)).unwrap().to_rgba8().get_pixel(200, 150).0; + let [r, g, b, _] = craft_image_codecs::decode(&decode(&png)) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() + .get_pixel(200, 150) + .0; assert!(near([r, g, b], RED), "{:?}", [r, g, b]); // Saved for older apps: the art it shows (here its preview), as plain objects. let old: Value = diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index a294cc9036..ff5f6a1dce 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -1157,9 +1157,41 @@ fn pathfinder_takes_swatch_linked_pieces_of_type_in_a_reshaped_group() { fn an_image_s_painted_fill_is_hit_and_measured_as_drawn() { let mut s = session(); let mut png = vec![]; - image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255]))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let r = run(&mut s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [65, 65]})); let im = NodeId(r["ids"][0].as_u64().unwrap()); run(&mut s, "swatch.new", json!({"name": "Leaf", "color": "#00ff00"})); diff --git a/crates/engine/src/tests/printadvanced.rs b/crates/engine/src/tests/printadvanced.rs index 8faa2f7adf..e183e7dfb2 100644 --- a/crates/engine/src/tests/printadvanced.rs +++ b/crates/engine/src/tests/printadvanced.rs @@ -171,7 +171,24 @@ fn print_as_bitmap_honours_rich_black() { } }); let bytes = &prepared.images[key.as_ref().expect("bitmap image")].bytes; - let img = image::load_from_memory(bytes).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); img.get_pixel(img.width() / 2, img.height() / 2).0 }; let accurate = centre(&crate::cmd::printadvanced::prepare("file.print", doc(&s), &set, &saved, false).unwrap().unwrap()); diff --git a/crates/engine/src/tests/rasterfilters.rs b/crates/engine/src/tests/rasterfilters.rs index 534f79b1bc..f0fccb140e 100644 --- a/crates/engine/src/tests/rasterfilters.rs +++ b/crates/engine/src/tests/rasterfilters.rs @@ -284,7 +284,41 @@ fn rings_png() -> Vec { image::Rgba([v as u8, v as u8, 255 - v as u8, 255]) }); let mut png = Vec::new(); - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); png } diff --git a/crates/engine/src/tests/rastersettings.rs b/crates/engine/src/tests/rastersettings.rs index 75659faf32..4b9313a79f 100644 --- a/crates/engine/src/tests/rastersettings.rs +++ b/crates/engine/src/tests/rastersettings.rs @@ -34,7 +34,24 @@ fn effect_image(doc: &Document) -> image::RgbaImage { let kids = flat.layers[0].children().unwrap(); let NodeKind::Group { children, .. } = &kids[0].kind else { panic!("a shadow becomes a group") }; let NodeKind::Image(im) = &children[0].kind else { panic!("the image goes under the object") }; - image::load_from_memory(&flat.images[&im.key].bytes).unwrap().to_rgba8() + craft_image_codecs::decode(&flat.images[&im.key].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() } #[test] @@ -167,7 +184,24 @@ fn the_color_model_and_anti_alias_reach_the_pixels() { let out = s.execute("object.rasterize", &json!({"colorModel": "rgb"})).unwrap(); let d = &s.doc().unwrap().doc; let NodeKind::Image(im) = &d.node(id(&out)).unwrap().kind else { panic!("an image") }; - let img = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&d.images[&im.key].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert!(img.pixels().all(|p| p[3] == 0 || p[3] == 255), "hard edges"); assert!(img.pixels().any(|p| p[3] == 0) && img.pixels().any(|p| p[3] == 255)); } @@ -184,7 +218,24 @@ fn rasterize_takes_the_document_settings_as_defaults() { assert_eq!((out["width"].as_u64(), out["height"].as_u64()), (Some(60), Some(60)), "10 pt around"); let d = &s.doc().unwrap().doc; let NodeKind::Image(im) = &d.node(id(&out)).unwrap().kind else { panic!("an image") }; - let img = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&d.images[&im.key].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!(img.get_pixel(0, 0).0, [255, 255, 255, 255], "white around the art"); let p = img.get_pixel(30, 30).0; assert!(p[0] == p[1] && p[1] == p[2] && p[0] < 128, "red in grayscale: {p:?}"); @@ -343,7 +394,24 @@ fn object_rasterize_takes_in_everything_an_effect_stack_paints() { let made = id(&s.execute("object.rasterize", &json!({"ppi": 72, "background": "transparent"})).unwrap()); let d = &s.doc().unwrap().doc; let (width, height, xf, png, _) = rasterized(d, d.node(made).unwrap()); - let img = image::load_from_memory(&png).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&png) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); // 41 pt of rectangle and stroke, and 6 pt of blur and 10 pt of white on each side: white from // the first column to the last. assert_eq!((width, xf.translation().x), (73, 34.0)); @@ -451,7 +519,24 @@ fn rasterize_to_cmyk_makes_a_cmyk_image() { let mask = masked.extras().mask.as_deref().expect("an opacity mask").clone(); let d = &s.doc().unwrap().doc; let NodeKind::Image(m) = &mask.art.kind else { panic!("the mask is an image") }; - let alpha = image::load_from_memory(&d.images[&m.key].bytes).unwrap().to_luma8(); + let alpha = craft_image_codecs::decode(&d.images[&m.key].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_luma8(); assert_eq!((alpha.get_pixel(1, 1).0, alpha.get_pixel(25, 25).0), ([0], [255])); assert!(mask.clip); } @@ -478,7 +563,24 @@ fn rasterize_to_grayscale_or_bitmap_makes_a_grayscale_image() { assert!(n.extras().mask.is_none(), "{mode} {model} {background}: no opacity mask"); let NodeKind::Image(im) = &n.kind else { panic!("an image") }; let blob = d.images[&im.key].clone(); - let pixels = image::load_from_memory(&blob.bytes).unwrap().to_luma_alpha8(); + let pixels = craft_image_codecs::decode(&blob.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_luma_alpha8(); assert_eq!(pixels.dimensions(), (50, 50)); let at = |x, y| pixels.get_pixel(x, y).0; s.execute("edit.undo", &json!({})).unwrap(); diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index 90e7822ef8..9c1149da68 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -1085,7 +1085,41 @@ fn global_adjust_refuses_params_of_the_wrong_form() { fn halves_image(s: &mut Session, w: u32, h: u32, left: [u8; 4], right: [u8; 4]) -> (NodeId, vectorcraft_geom::Rect) { let img = image::RgbaImage::from_fn(w, h, |x, _| image::Rgba(if x < w / 2 { left } else { right })); let mut png = Vec::new(); - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let r = run(s, "file.place", json!({"name": "halves.png", "dataBase64": vectorcraft_format::base64_encode(&png)})); let id = NodeId(r["ids"][0].as_u64().unwrap()); let b = s.doc().unwrap().doc.node(id).unwrap().visual_bounds().unwrap(); @@ -1210,7 +1244,41 @@ fn theme_picker_reads_symbol_art_and_nested_patterns() { fn theme_picker_reads_the_color_of_a_colorized_image() { let mut s = session(); let mut png = Vec::new(); - image::GrayImage::from_pixel(8, 8, image::Luma([90])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::GrayImage::from_pixel(8, 8, image::Luma([90]))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let r = run(&mut s, "file.place", json!({"name": "gray.png", "dataBase64": vectorcraft_format::base64_encode(&png)})); let id = NodeId(r["ids"][0].as_u64().unwrap()); let b = s.doc().unwrap().doc.node(id).unwrap().visual_bounds().unwrap(); @@ -1265,7 +1333,41 @@ fn theme_picker_reads_an_image_inside_its_clipping_path() { image::Rgba(if corner { [0, 0, 255, 255] } else { [255, 0, 0, 255] }) }); let mut png = Vec::new(); - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let r = run(&mut s, "file.place", json!({"name": "corners.png", "dataBase64": vectorcraft_format::base64_encode(&png)})); let id = NodeId(r["ids"][0].as_u64().unwrap()); let b = s.doc().unwrap().doc.node(id).unwrap().visual_bounds().unwrap(); diff --git a/crates/engine/src/tests/save.rs b/crates/engine/src/tests/save.rs index 99febca6b2..076e964212 100644 --- a/crates/engine/src/tests/save.rs +++ b/crates/engine/src/tests/save.rs @@ -760,7 +760,23 @@ fn eps_save_bounds_large_page_preview_without_cropping_vector_or_editing_data() let (ps, tiff) = vectorcraft_eps::sections(&bytes).unwrap(); let tiff = tiff.unwrap(); assert!(tiff.len() < 4 * 1024 * 1024 + 64 * 1024, "compatibility preview grew to {} bytes", tiff.len()); - let preview = image::load_from_memory_with_format(tiff, image::ImageFormat::Tiff).unwrap(); + let preview = craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, tiff) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap(); assert_eq!((preview.width(), preview.height()), (1024, 1024)); assert!(std::str::from_utf8(ps).unwrap().contains("%%BoundingBox: 0 0 4000 4000")); let native = vectorcraft_format::load(&vectorcraft_eps::native(&bytes).unwrap()).unwrap(); diff --git a/crates/engine/src/tests/select_effects.rs b/crates/engine/src/tests/select_effects.rs index d2160fba34..c455180d2d 100644 --- a/crates/engine/src/tests/select_effects.rs +++ b/crates/engine/src/tests/select_effects.rs @@ -168,9 +168,41 @@ fn a_click_on_the_drop_shadow_of_a_symbols_art_does_not_select_the_instance() { fn a_click_on_the_drop_shadow_of_an_image_outside_its_frame_does_not_select_it() { let mut s = session(); let mut png = vec![]; - image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255]))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let r = run(&mut s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [65, 65]})); let im = NodeId(r["ids"][0].as_u64().unwrap()); // The frame lies from x 50 to 80 and the shadow from 90 to 120. diff --git a/crates/engine/src/tests/symbolbounds.rs b/crates/engine/src/tests/symbolbounds.rs index 5140d5630f..50adeededb 100644 --- a/crates/engine/src/tests/symbolbounds.rs +++ b/crates/engine/src/tests/symbolbounds.rs @@ -506,7 +506,24 @@ fn a_copied_instances_png_is_cropped_to_its_art() { let r = run(&mut s, "clipboard.exportPng", json!({})); assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(40), Some(20))); let png = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); - let img = image::load_from_memory(&png).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&png) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!(img.get_pixel(20, 10).0, [0, 0, 0, 255], "the art fills the picture"); } diff --git a/crates/engine/src/tests/warp_images.rs b/crates/engine/src/tests/warp_images.rs index 9dc781ee16..4fc09f7d84 100644 --- a/crates/engine/src/tests/warp_images.rs +++ b/crates/engine/src/tests/warp_images.rs @@ -34,7 +34,41 @@ fn quarters(s: &mut Session) -> NodeId { image::Rgba([r, g, b, 255]) }); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); s.edit("Place", |d, sel| { d.images.insert("quarters".into(), vectorcraft_doc::ImageBlob::png(png)); let id = d.alloc_id(); @@ -168,7 +202,24 @@ fn a_warped_image_keeps_its_bend_in_png() { let mut s = session(); arc_image(&mut s); let out = s.execute("document.export", &json!({"format": "png"})).unwrap(); - let png = image::load_from_memory(&decoded(&out)).unwrap().to_rgba8(); + let png = craft_image_codecs::decode(&decoded(&out)) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); // The artboard starts at (0, 0) and the export draws one pixel a point. assert_eq!((png.width(), png.height()), (800, 600)); for &(u, v) in &SAMPLES { @@ -241,7 +292,41 @@ fn expand_appearance_of_a_warped_image_draws_as_the_canvas_did() { fn red_on_clear(s: &mut Session) -> NodeId { let img = image::GrayImage::from_fn(40, 40, |_, y| image::Luma([if y < 20 { 0 } else { 255 }])); let mut png = vec![]; - image::DynamicImage::ImageLuma8(img).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::DynamicImage::ImageLuma8(img)).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let id = s .edit("Place", |d, sel| { d.images.insert("gray".into(), vectorcraft_doc::ImageBlob::png(png)); @@ -302,7 +387,41 @@ fn half_clear_arc(s: &mut Session) { fn clear_arc(s: &mut Session, alpha: impl Fn(u32) -> u8) { let img = image::RgbaImage::from_fn(40, 40, |x, _| image::Rgba([255, 0, 0, alpha(x)])); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); s.edit("Place", |d, sel| { d.images.insert("half".into(), vectorcraft_doc::ImageBlob::png(png)); let id = d.alloc_id(); diff --git a/crates/engine/src/tests/webexport.rs b/crates/engine/src/tests/webexport.rs index cf427f8174..ccd20e119c 100644 --- a/crates/engine/src/tests/webexport.rs +++ b/crates/engine/src/tests/webexport.rs @@ -64,7 +64,24 @@ fn one(s: &mut Session, p: Value) -> Vec { } fn pixels(file: &[u8]) -> image::RgbaImage { - image::load_from_memory(file).unwrap().to_rgba8() + craft_image_codecs::decode(file) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() } fn distinct(img: &image::RgbaImage) -> usize { diff --git a/crates/engine/tests/affinity_corpus.rs b/crates/engine/tests/affinity_corpus.rs index f92403d086..c1dac68981 100644 --- a/crates/engine/tests/affinity_corpus.rs +++ b/crates/engine/tests/affinity_corpus.rs @@ -81,7 +81,24 @@ fn public_affinity_documents_render_like_their_affinity_thumbnails() { let loaded = vectorcraft_engine::cmd::fileio::load(name, &bytes).unwrap(); assert!(!loaded.preview_only, "{name} opened as its preview: {:?}", loaded.warnings); let d = &loaded.doc; - let thumb = image::load_from_memory(vectorcraft_affinity::preview(&bytes).unwrap().png).unwrap().to_rgba8(); + let thumb = craft_image_codecs::decode(vectorcraft_affinity::preview(&bytes).unwrap().png) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); // The embedded thumbnail shows the union of the artboards. Check every board, // including small ones that the previous largest-board-only check omitted. let union = d.artboards.iter().map(|a| a.rect).reduce(|a, b| a.union(b)).unwrap(); @@ -166,7 +183,24 @@ fn affinity3_all_artboards_survive_native_save_and_export() { assert_eq!(vectorcraft_pdf::import(&pdf).unwrap().artboards.len(), 1, "{name} board {index}: PDF reimport"); let psd = vectorcraft_engine::cmd::fileio::encode(doc, "psd", ¶ms).unwrap(); let png = vectorcraft_engine::cmd::fileio::encode(doc, "png", ¶ms).unwrap(); - let png = image::load_from_memory(&png).unwrap().to_rgba8(); + let png = craft_image_codecs::decode(&png) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); let (merged, has_alpha) = psd_merged(&psd); assert_eq!(merged.dimensions(), png.dimensions(), "{name} board {index}: PSD image dimensions"); // PSD merged RGB is stored on a white matte for readers that ignore alpha; diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index b02e34690b..3565e57364 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -558,7 +558,41 @@ fn the_eyedropper_takes_an_image_pixel_into_the_working_rgb_space() { let mut s = session(); let img = image::RgbaImage::from_raw(1, 1, vec![83, 170, 223, 255]).unwrap(); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); s.edit("Place", |d, _| { d.images.insert("px".into(), ImageBlob::png(png)); let l = d.layers[0].id; @@ -653,7 +687,24 @@ fn freeform_rgb_points_mix_in_the_working_rgb_space() { let canvas = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &opts).pixel(50, 50); let svg = vectorcraft_svg::export_full(&d, &vectorcraft_svg::ExportOptions::default(), None).svg; let data = svg.split("data:image/png;base64,").nth(1).unwrap().split('"').next().unwrap(); - let png = image::load_from_memory(&vectorcraft_testkit::format::base64_decode(data).unwrap()).unwrap().to_rgba8(); + let png = craft_image_codecs::decode(&vectorcraft_testkit::format::base64_decode(data).unwrap()) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); let written = png.get_pixel(png.width() / 2, png.height() / 2).0; let want = Color::rgb(0.5, 0.15, 0.5).to_rgba8(1.0); let display = f.field(spread_scale(box_)).sample(Point::new(50.5, 50.5)).0.map(|v| (v * 255.0).round() as u8); diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 797ca39f52..6dd92b0d6d 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -1360,7 +1360,41 @@ fn gradient_mesh_from_images_with_junk_params() { use vectorcraft_geom::Affine; let img = image::RgbaImage::from_fn(5, 3, |x, y| image::Rgba([x as u8 * 50, y as u8 * 90, 7, if x == 2 { 0 } else { 255 }])); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let params = [ json!({}), json!({"rows": 1, "cols": 1}), diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 7e613460cd..dc12f580da 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -37,7 +37,41 @@ fn config() -> ProptestConfig { fn affinity_preview_sample() -> Vec { let im = image::RgbaImage::from_pixel(2, 1, image::Rgba([220, 40, 60, 255])); let mut png = Vec::new(); - im.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (im).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let mut b = vec![0; 72]; b[..4].copy_from_slice(vectorcraft_affinity::MAGIC); b[4..6].copy_from_slice(&12u16.to_le_bytes()); @@ -1730,13 +1764,46 @@ fn raster_samples() -> Vec<(&'static str, Vec)> { let img = image::RgbImage::from_pixel(5, 3, image::Rgb([200, 40, 10])); let mut out = vec![]; for (name, f) in [ - ("a.png", image::ImageFormat::Png), - ("a.jpg", image::ImageFormat::Jpeg), - ("a.tif", image::ImageFormat::Tiff), - ("a.bmp", image::ImageFormat::Bmp), + ("a.png", craft_image_codecs::Format::Png), + ("a.jpg", craft_image_codecs::Format::Jpeg), + ("a.tif", craft_image_codecs::Format::Tiff), + ("a.bmp", craft_image_codecs::Format::Bmp), ] { let mut b = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut b), f).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, f, &craft_image_codecs::EncodeOptions::default()).map(|__b| b.extend_from_slice(&__b)) + } + .unwrap(); out.push((name, b)); } out[0].1 = vectorcraft_engine::cmd::fileio::ppi::with_png_resolution(&out[0].1, (300.0, 150.0)); @@ -1765,14 +1832,12 @@ fn raster_samples() -> Vec<(&'static str, Vec)> { psb.extend((0..8u8).flat_map(|v| [0xfe, v * 30])); out.push(("a.psb", psb)); // JPEG XL: an 8-bit RGBA codestream, and a 16-bit gray one in the container. - use zune_core::{bit_depth::BitDepth, colorspace::ColorSpace, options::EncoderOptions}; - let jxl = |space, depth, samples: &[u8]| { - let mut b = vec![]; - zune_jpegxl::JxlSimpleEncoder::new(samples, EncoderOptions::new(5, 3, space, depth)).encode(&mut b).unwrap(); - b - }; - out.push(("a.jxl", jxl(ColorSpace::RGBA, BitDepth::Eight, &(0..60).map(|i| (i * 17) as u8).collect::>()))); - let gray = jxl(ColorSpace::Luma, BitDepth::Sixteen, &(0..30).map(|i| (i * 41) as u8).collect::>()); + use craft_jxl::{EncodeOptions, ImageRef, Layout, Samples}; + let opts = EncodeOptions { lossless: true, ..EncodeOptions::default() }; + let rgba: Vec = (0..60).map(|i| (i * 17) as u8).collect(); + out.push(("a.jxl", craft_jxl::encode(ImageRef { width: 5, height: 3, layout: Layout::Rgba, samples: Samples::U8(&rgba) }, opts).unwrap())); + let gray_u16: Vec = (0..15).map(|i| u16::from_ne_bytes([(i * 2 * 41) as u8, ((i * 2 + 1) * 41) as u8])).collect(); + let gray = craft_jxl::encode(ImageRef { width: 5, height: 3, layout: Layout::Gray, samples: Samples::U16(&gray_u16) }, opts).unwrap(); let mut boxed = vec![0, 0, 0, 0x0c, b'J', b'X', b'L', b' ', 0x0d, 0x0a, 0x87, 0x0a]; boxed.extend(20u32.to_be_bytes()); boxed.extend(b"ftypjxl \0\0\0\0jxl "); @@ -1885,7 +1950,41 @@ proptest! { /// and a 32-bit one with an extension area. fn targa_samples() -> Vec<(&'static str, Vec)> { let mut rle = vec![]; - image::RgbImage::from_pixel(5, 3, image::Rgb([200, 40, 10])).write_to(&mut std::io::Cursor::new(&mut rle), image::ImageFormat::Tga).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbImage::from_pixel(5, 3, image::Rgb([200, 40, 10]))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Tga, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| rle.extend_from_slice(&__b)) + } + .unwrap(); let mut s = rich_session(); let r = s.execute("document.export", &json!({"format": "tga", "depth": 16, "ppi": 2})).unwrap(); let export = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); @@ -2574,7 +2673,24 @@ fn the_ccitt_images_fixture_reads_both_images() { let mut found = vec![]; d.walk(|n| { if let vectorcraft_doc::NodeKind::Image(im) = &n.kind { - let px = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8(); + let px = craft_image_codecs::decode(&d.images[&im.key].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); found.push(px.pixels().map(shade).collect::()); } }); diff --git a/crates/engine/tests/it/affinity_features.rs b/crates/engine/tests/it/affinity_features.rs index 6a0338ee17..98fdbe6b23 100644 --- a/crates/engine/tests/it/affinity_features.rs +++ b/crates/engine/tests/it/affinity_features.rs @@ -670,7 +670,24 @@ fn cmyk_pixel_layers_show_through_the_documents_cmyk_profile() { let loaded = open("photo.af", &cmyk_layer(false, Some(&icc))); let blob = photo(&loaded.doc); assert!(!blob.is_cmyk()); - let px = image::load_from_memory(&blob.bytes).unwrap().to_rgba8(); + let px = craft_image_codecs::decode(&blob.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); let profile = IccProfile::from_bytes(None, &icc).unwrap(); let srgb = cms::icc::builtin_rgb(cms::SRGB).unwrap(); let want = profile.to_rgb_of(&srgb, &[1.0, 0.0, 0.0, 0.0], Intent::RelativeColorimetric, true).unwrap().map(|v| (v * 255.0).round() as i32); @@ -691,7 +708,29 @@ fn cmyk_pixel_layers_without_a_profile_keep_their_inks_or_use_the_working_profil let loaded = open("photo.af", &cmyk_layer(true, None)); let blob = photo(&loaded.doc); assert!(!blob.is_cmyk()); - assert_eq!(image::load_from_memory(&blob.bytes).unwrap().to_rgba8().get_pixel(8, 8).0[3], 0); + assert_eq!( + craft_image_codecs::decode(&blob.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() + .get_pixel(8, 8) + .0[3], + 0 + ); assert!(loaded.warnings.iter().any(|w| w.contains("CMYK pixel layers with transparency")), "{:?}", loaded.warnings); } diff --git a/crates/engine/tests/it/affinity_local.rs b/crates/engine/tests/it/affinity_local.rs index c0ae237e99..54df4a4612 100644 --- a/crates/engine/tests/it/affinity_local.rs +++ b/crates/engine/tests/it/affinity_local.rs @@ -45,7 +45,24 @@ fn local_affinity_documents_render_like_their_thumbnails() { eprintln!(" {w}"); } let Ok(preview) = vectorcraft_affinity::preview(&bytes) else { continue }; - let thumb = image::load_from_memory(preview.png).unwrap().to_rgba8(); + let thumb = craft_image_codecs::decode(preview.png) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); let union = d.artboards.iter().map(|a| a.rect).reduce(|a, b| a.union(b)).unwrap(); let scale = f64::from(thumb.width()) / union.width(); let mut total = 0.0; diff --git a/crates/engine/tests/open_relative_path.rs b/crates/engine/tests/open_relative_path.rs index f0c63a0fb9..a9cccf5bb9 100644 --- a/crates/engine/tests/open_relative_path.rs +++ b/crates/engine/tests/open_relative_path.rs @@ -12,7 +12,41 @@ fn a_relative_path_finds_relative_links() { let dir = std::env::temp_dir().join(format!("vectorcraft-relative-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let mut png = Vec::new(); - image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, 255]))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); std::fs::write(dir.join("ext.png"), &png).unwrap(); let svg = r#""#; std::fs::write(dir.join("linked.svg"), svg).unwrap(); diff --git a/crates/engine/tests/plugin_export.rs b/crates/engine/tests/plugin_export.rs index 94618ee84d..607b17d468 100644 --- a/crates/engine/tests/plugin_export.rs +++ b/crates/engine/tests/plugin_export.rs @@ -83,7 +83,41 @@ fn the_exporter_is_given_the_native_file_s_json() { image::Rgba([r, g, b, 255]) }); let mut png = vec![]; - noise.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (noise).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); assert!(png.len() >= vectorcraft_format::INLINE_MAX, "{} bytes", png.len()); s.execute("file.place", &json!({"name": "noise.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); diff --git a/crates/engine/tests/plugin_import.rs b/crates/engine/tests/plugin_import.rs index f091062308..4f336ef806 100644 --- a/crates/engine/tests/plugin_import.rs +++ b/crates/engine/tests/plugin_import.rs @@ -393,7 +393,41 @@ fn a_built_in_file_past_the_input_limit_still_opens() { echo(&mut s, "test.largepng", r#"["tsp"]"#); let path = dir.join("big.tsp"); let mut png = std::io::Cursor::new(vec![]); - image::RgbaImage::new(2, 2).write_to(&mut png, image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::new(2, 2)).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); std::fs::write(&path, png.get_ref()).unwrap(); std::fs::OpenOptions::new().write(true).open(&path).unwrap().set_len(vectorcraft_plugins::import::MAX_INPUT_BYTES as u64 + 1).unwrap(); let e = s.execute("document.open", &json!({"path": path_of(&path), "importer": "plugin.test.largepng"})).unwrap_err(); diff --git a/crates/eps/Cargo.toml b/crates/eps/Cargo.toml index bd173588aa..9efae37385 100644 --- a/crates/eps/Cargo.toml +++ b/crates/eps/Cargo.toml @@ -30,10 +30,11 @@ craft-pdf = { workspace = true } vectorcraft-render = { workspace = true } kurbo = { workspace = true } image = { workspace = true } +craft-image-codecs = { workspace = true } flate2 = { workspace = true } ruzstd = { workspace = true } # Images read through `CCITTFaxDecode`. -hayro-ccitt = { workspace = true } +craft-stream-codecs = { workspace = true } # Live effects' params, as the art styles that name them give them. serde_json = { workspace = true } # Substring search for PostScript `search`. diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 59b6b04e4e..628ba6fe50 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -800,7 +800,41 @@ fn unsupported() -> Document { doc.insert(Some(layer), usize::MAX, ring).unwrap(); let mut png = vec![]; let img = image::RgbaImage::from_raw(2, 1, vec![255, 0, 0, 255, 0, 0, 255, 255]).unwrap(); - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); doc.images.insert(key.clone(), blob); @@ -1348,7 +1382,41 @@ fn an_adjusted_image_in_a_symbol_is_written_in_its_adjusted_color() { let mut doc = Document::new(200.0, 100.0); let layer = doc.layers[0].id; let mut png = vec![]; - image::RgbaImage::from_pixel(2, 2, image::Rgba([0, 0, 0, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(2, 2, image::Rgba([0, 0, 0, 255]))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); doc.images.insert(key.clone(), blob); @@ -1508,7 +1576,41 @@ fn effects_on_a_fill_are_reported_left_out() { #[test] fn images_of_more_pixels_than_the_reader_reads_are_mid_gray() { let mut png = vec![]; - image::GrayImage::new(6000, 6000).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::GrayImage::new(6000, 6000)).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let mut doc = Document::new(200.0, 100.0); let layer = doc.layers[0].id; let im = image_node(&mut doc, ImageBlob::png(png), (10, 10), Affine::IDENTITY, None); @@ -3110,7 +3212,41 @@ fn a_pattern_swatchs_own_placement_is_reported_left_out() { /// `img` as PNG bytes. fn png_of(img: image::DynamicImage) -> Vec { let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); png } @@ -3187,7 +3323,28 @@ fn pictures(doc: &Document, nodes: &[Arc], path: &str, out: &mut Vec format!("cmyk {:?}", inks.data), - _ => format!("rgba {:?}", image::load_from_memory(&blob.bytes).unwrap().to_rgba8().into_raw()), + _ => format!( + "rgba {:?}", + craft_image_codecs::decode(&blob.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() + .into_raw() + ), }; let xf: Vec = im.xf.as_coeffs().iter().map(|v| r3(*v)).collect(); let link = im.link.as_ref().map(|l| (l.path.clone(), l.relative.clone())); @@ -3470,7 +3627,24 @@ fn a_smaller_preview_takes_no_color_from_see_through_pixels() { let back = read_back(&doc); let NodeKind::Image(im) = &back.layers[0].children().unwrap()[0].kind else { panic!("not an image") }; assert_eq!(im.width, 256); - let px = image::load_from_memory(&back.image_blob(im).unwrap().bytes).unwrap().to_rgba8(); + let px = craft_image_codecs::decode(&back.image_blob(im).unwrap().bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert!(px.pixels().all(|p| p.0[0] == 0), "{:?}", px.pixels().take(4).collect::>()); assert!(px.pixels().filter(|p| p.0[3] > 0).count() > 400); } @@ -4857,7 +5031,43 @@ fn beside(doc: &mut Document, kind: Beside, x: f64, state: (f32, BlendMode, bool Beside::Image => { let mut png = vec![]; let img = image::RgbaImage::from_raw(1, 1, vec![255, 0, 0, 255]).unwrap(); - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => { + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()) + } + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); doc.images.insert(key.clone(), blob); diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index 6361efe5ff..2bd86ece43 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -1768,16 +1768,13 @@ pub(super) fn hide(text: &str, out: &mut String) { /// The image `bytes` decoded, when its header gives at most `max` pixels; the decoder may allocate /// at most 8 bytes a pixel. fn decode_bounded(bytes: &[u8], max: u64) -> Option { - let reader = || -> image::ImageResult>> { - let mut r = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format()?; - let mut limits = image::Limits::default(); - limits.max_alloc = Some(max * 8); - r.limits(limits); - Ok(r) - }; - let (w, h) = reader().and_then(|r| r.into_dimensions()).ok()?; + let mut opts = craft_image_codecs::DecodeOptions::default(); + opts.limits.max_pixels = max; + opts.limits.max_alloc = max * 8; + let img = craft_image_codecs::decode_with(bytes, &opts).ok()?; + let (w, h) = img.dimensions(); if u64::from(w) * u64::from(h) > max { return None; } - reader().and_then(|r| r.decode()).ok() + image::RgbaImage::from_raw(w, h, img.to_rgba8()).map(image::DynamicImage::ImageRgba8) } diff --git a/crates/eps/src/import/ai/read/art.rs b/crates/eps/src/import/ai/read/art.rs index 3338968895..561f99c597 100644 --- a/crates/eps/src/import/ai/read/art.rs +++ b/crates/eps/src/import/ai/read/art.rs @@ -544,15 +544,20 @@ impl<'a> Reader<'a> { rgba.extend_from_slice(&[px[0], px[1], px[2], a]); } } - let Some(img) = image::RgbaImage::from_raw(w as u32, h as u32, rgba) else { + let Ok(img) = craft_image_codecs::Image::from_raw( + w as u32, + h as u32, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + rgba, + ) else { self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); }; - let mut png = vec![]; - if img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).is_err() { + let Ok(png) = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) else { self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); - } + }; self.add_raster(ImageBlob::new("image/png", png), None, &m, (w as u32, h as u32), None) } @@ -577,12 +582,13 @@ impl<'a> Reader<'a> { gray.push(v); } } - let mut png = vec![]; - let written = image::GrayImage::from_raw(w, h, gray).map(|img| img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)); - if !matches!(written, Some(Ok(()))) { + let written = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, gray) + .ok() + .and_then(|img| craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()); + let Some(png) = written else { self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); - } + }; self.add_raster(ImageBlob::new("image/png", png), alpha, m, (w, h), Some(paint)) } @@ -670,15 +676,16 @@ impl<'a> Reader<'a> { let blob = if cmyk { Inks::new(ow, oh, pixels).and_then(|i| ImageBlob::cmyk_tiff(&i)) } else { - use image::ImageEncoder as _; - let colour = match (s.channels, inline && opacity.is_some()) { - (1, false) => image::ExtendedColorType::L8, - (1, true) => image::ExtendedColorType::La8, - (_, false) => image::ExtendedColorType::Rgb8, - (_, true) => image::ExtendedColorType::Rgba8, + let layout = match (s.channels, inline && opacity.is_some()) { + (1, false) => craft_image_codecs::ChannelLayout::Gray, + (1, true) => craft_image_codecs::ChannelLayout::GrayA, + (_, false) => craft_image_codecs::ChannelLayout::Rgb, + (_, true) => craft_image_codecs::ChannelLayout::Rgba, }; - let mut png = vec![]; - image::codecs::png::PngEncoder::new(&mut png).write_image(&pixels, ow, oh, colour).ok().map(|()| ImageBlob::new("image/png", png)) + craft_image_codecs::Image::from_raw(ow, oh, layout, craft_image_codecs::SampleType::U8, pixels) + .ok() + .and_then(|img| craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()) + .map(|png| ImageBlob::new("image/png", png)) }; // One that can't be encoded is left to the page's art, as one past the hard limits. let Some(blob) = blob else { @@ -766,8 +773,10 @@ impl<'a> Reader<'a> { if alpha.iter().all(|v| *v == 255) { return None; } - let mut png = Vec::new(); - image::GrayImage::from_raw(w, h, alpha.to_vec())?.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).ok()?; + let raw = + craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, alpha.to_vec()) + .ok()?; + let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); self.doc.images.entry(key.clone()).or_insert(blob); @@ -1024,8 +1033,9 @@ pub(super) fn preview_png(data: &[u8]) -> Option<(Vec, u32, u32)> { rgba.extend_from_slice(&[straight(r), straight(g), straight(b), a]); } } - let mut png = vec![]; - image::RgbaImage::from_raw(width, height, rgba)?.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).ok()?; + let raw = + craft_image_codecs::Image::from_raw(width, height, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba).ok()?; + let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; Some((png, width, height)) } diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index d160248a2d..1f03e367fe 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -2676,7 +2676,27 @@ fn pixels(doc: &Document) -> (image::RgbaImage, kurbo::Affine) { let a = art(doc); let NodeKind::Image(im) = &a[0].kind else { panic!("{:?}", a[0].kind) }; let blob = doc.images.get(&im.key).unwrap(); - (image::load_from_memory(&blob.bytes).unwrap().to_rgba8(), im.xf) + ( + craft_image_codecs::decode(&blob.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(), + im.xf, + ) } /// A 1-bit image's row holds each pixel's channels in turn, one bit each, padded to whole bytes; @@ -3073,7 +3093,24 @@ fn cmyk_images_keep_their_ink_amounts() { assert!(m.clip); let NodeKind::Image(mi) = &m.art.kind else { panic!("{:?}", m.art.kind) }; assert_eq!((mi.width, mi.height, mi.xf), (3, 1, im.xf), "the mask covers the image"); - let gray = image::load_from_memory(&doc.images[&mi.key].bytes).unwrap().to_luma8(); + let gray = craft_image_codecs::decode(&doc.images[&mi.key].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_luma8(); assert_eq!(gray.into_raw(), [255, 128, 0]); // An alpha channel that hides nothing adds no mask. let data = [&inks[..], &[255; 3]].concat(); diff --git a/crates/eps/src/import/data.rs b/crates/eps/src/import/data.rs index 53848af89d..24e7990dd2 100644 --- a/crates/eps/src/import/data.rs +++ b/crates/eps/src/import/data.rs @@ -5,7 +5,7 @@ use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; -use hayro_ccitt::{DecodeSettings, Decoder, DecoderContext, EncodingMode}; +use craft_stream_codecs::CcittParams; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::cmyk::{Inks, jpeg_components}; use vectorcraft_doc::{ImageBlob, ImageObject, Node, NodeId, NodeKind, OpacityMask}; diff --git a/crates/eps/src/import/data/filters.rs b/crates/eps/src/import/data/filters.rs index 79dce67ea0..2b93fb1082 100644 --- a/crates/eps/src/import/data/filters.rs +++ b/crates/eps/src/import/data/filters.rs @@ -1,8 +1,5 @@ use super::ops::MAX_DATA; -use super::{ - DecodeSettings, Decoder, DecoderContext, DictRef, EncodingMode, ImageBlob, Key, Obj, PsError, Rc, RefCell, Res, find, hex_decode, - jpeg_components, ps, ps_err, -}; +use super::{CcittParams, DictRef, ImageBlob, Key, Obj, PsError, Rc, RefCell, Res, find, hex_decode, jpeg_components, ps, ps_err}; /// A file object: the program itself, or data a filter decoded. #[derive(Debug)] @@ -149,12 +146,26 @@ fn dct(raw: &[u8]) -> Res<(Vec, usize, u8)> { } // The header's size is checked before the decoder allocates for it (a progressive JPEG keeps its // coefficients besides its output). - let size = image::ImageReader::with_format(std::io::Cursor::new(jpeg), image::ImageFormat::Jpeg).into_dimensions(); - if size.is_ok_and(|(w, h)| u64::from(w) * u64::from(h) > MAX_DCT_PIXELS) { - return Err(PsError::Limit("decoded data is too large")); + let mut opts = craft_image_codecs::DecodeOptions::default(); + opts.limits.max_pixels = MAX_DCT_PIXELS; + let img = match craft_image_codecs::decode_as_with(craft_image_codecs::Format::Jpeg, jpeg, &opts) { + Ok(img) => img, + Err(craft_image_codecs::CodecError::LimitExceeded(_)) => return Err(PsError::Limit("decoded data is too large")), + Err(_) => return Err(PsError::Ps("ioerror", "DCTDecode".into())), + }; + if img.layout() == craft_image_codecs::ChannelLayout::Gray { + let (w, h) = img.dimensions(); + let gray = if img.sample_type() == craft_image_codecs::SampleType::U8 { + img.into_data() + } else { + img.to_rgba8().chunks_exact(4).map(|p| p[0]).collect() + }; + if gray.len() == (w as usize) * (h as usize) { + return Ok((gray, end, 1)); + } } - let img = image::load_from_memory_with_format(jpeg, image::ImageFormat::Jpeg).map_err(|_| PsError::Ps("ioerror", "DCTDecode".into()))?; - if img.color().channel_count() == 1 { Ok((img.to_luma8().into_raw(), end, 1)) } else { Ok((img.to_rgb8().into_raw(), end, 3)) } + let rgb: Vec = img.to_rgba8().chunks_exact(4).flat_map(|p| [p[0], p[1], p[2]]).collect(); + Ok((rgb, end, 3)) } /// CCITT fax data (ITU-T T.4 Group 3, one- or two-dimensional, and T.6 Group 4) decoded to rows @@ -163,36 +174,25 @@ fn dct(raw: &[u8]) -> Res<(Vec, usize, u8)> { /// `Rows`; without it they end after `Rows` rows, or at the end of the data when `Rows` is 0. /// Damaged data ends the rows: those decoded before it are kept, and damage in the first row is an /// `ioerror`. Rows that would take more than `MAX_DATA` bytes are refused. -fn fax(raw: &[u8], settings: DecodeSettings) -> Res<(Vec, usize)> { +fn fax(raw: &[u8], settings: CcittParams) -> Res<(Vec, usize)> { let row = (settings.columns as usize).div_ceil(8).max(1); let most = u32::try_from(MAX_DATA / row).unwrap_or(u32::MAX); - if !settings.end_of_block && settings.rows > most { + if !settings.end_of_block && settings.rows > i64::from(most) { return Err(PsError::Limit("decoded data is too large")); } // Without a row count that ends the data, a row past `most` shows that the data is too large. - let rows = if settings.end_of_block || settings.rows == 0 { most.saturating_add(1) } else { settings.rows }; + let rows = if settings.end_of_block || settings.rows == 0 { most.saturating_add(1) } else { settings.rows as u32 }; // The decoder reads the RTC of Group 3 two-dimensional data as rows: it gets the data before it. - let rtc = match settings.encoding { - EncodingMode::Group3_2D { .. } if settings.end_of_block => rtc(raw), - _ => None, - }; + let rtc = if settings.k > 0 && settings.end_of_block { rtc(raw) } else { None }; let data = rtc.and_then(|(cut, _)| raw.get(..cut)).unwrap_or(raw); - let mut out = FaxRows::default(); - let read = hayro_ccitt::decode(data, &mut out, &mut DecoderContext::new(DecodeSettings { rows, ..settings })); - if out.rows > most { + let out = craft_stream_codecs::decode_ccitt_raw(data, &settings, rows).map_err(|_| PsError::Limit("decoded data is too large"))?; + if out.rows_decoded > most { return Err(PsError::Limit("decoded data is too large")); } - let used = match read { - Ok(used) => used, - Err(_) if out.rows > 0 => { - out.data.truncate(out.rows as usize * row); - // The whole rows decoded again, for how many bytes they took. - let used = hayro_ccitt::decode(data, &mut Dropped, &mut DecoderContext::new(DecodeSettings { rows: out.rows, ..settings })); - used.unwrap_or(data.len()) - } - Err(_) => return io("CCITTFaxDecode"), - }; - Ok((out.data, rtc.map_or(used, |(_, end)| end))) + if out.error.is_some() && out.rows_decoded == 0 { + return io("CCITTFaxDecode"); + } + Ok((out.data, rtc.map_or(out.bytes_consumed, |(_, end)| end))) } /// The RTC that ends Group 3 two-dimensional data (six EOLs, each followed by a 1 tag bit, ITU-T @@ -225,50 +225,6 @@ fn rtc(raw: &[u8]) -> Option<(usize, usize)> { None } -/// Rows of 1-bit samples from a CCITT decoder, each padded to a whole byte: 1 is white, or black -/// with `BlackIs1`. -#[derive(Default)] -struct FaxRows { - data: Vec, - /// Samples in the row being decoded. - x: u32, - /// Whole rows decoded. - rows: u32, -} - -impl Decoder for FaxRows { - fn push_pixel(&mut self, white: bool) { - if self.x.is_multiple_of(8) { - self.data.push(0); - } - if white && let Some(b) = self.data.last_mut() { - *b |= 0x80 >> (self.x % 8); - } - self.x = self.x.saturating_add(1); - } - - fn push_pixel_chunk(&mut self, white: bool, chunk_count: u32) { - self.data.extend(std::iter::repeat_n(if white { 0xff } else { 0 }, chunk_count as usize)); - self.x = self.x.saturating_add(chunk_count.saturating_mul(8)); - } - - fn next_line(&mut self) { - self.x = 0; - self.rows = self.rows.saturating_add(1); - } -} - -/// A CCITT decoder that drops what it decodes. -struct Dropped; - -impl Decoder for Dropped { - fn push_pixel(&mut self, _: bool) {} - - fn push_pixel_chunk(&mut self, _: bool, _: u32) {} - - fn next_line(&mut self) {} -} - /// A decoding filter and its parameters. #[derive(Clone, Debug)] pub(crate) struct Filter { @@ -278,7 +234,7 @@ pub(crate) struct Filter { /// `FlateDecode`'s and `LZWDecode`'s `Predictor`: what it undoes. pub(super) predictor: Option, /// `CCITTFaxDecode`'s parameters. - pub(super) fax: Option, + pub(super) fax: Option, } /// A `Predictor` (2: TIFF, 10–15: PNG) with its `Colors`, `BitsPerComponent` and `Columns`. @@ -407,7 +363,7 @@ fn paeth(a: u8, b: u8, c: u8) -> u8 { /// §7.4.6): `K` (below 0 Group 4, 0 Group 3 one-dimensional, above 0 Group 3 mixed), `Columns`, /// `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1`, with their defaults where /// `d` leaves them out. `Columns` outside 1 to 65,535 and `Rows` below 0 are a `rangecheck`. -pub(super) fn fax_settings(d: Option<&DictRef>) -> Res { +pub(super) fn fax_settings(d: Option<&DictRef>) -> Res { let get = |k: &str| d.and_then(|d| d.borrow().get(&Key::name(k)).cloned()); let num = |k: &str, default: f64| get(k).and_then(|o| o.as_num()).unwrap_or(default); let flag = |k: &str, default: bool| match get(k) { @@ -418,21 +374,21 @@ pub(super) fn fax_settings(d: Option<&DictRef>) -> Res { if !k.is_finite() || !(1.0..=65_535.0).contains(&columns) || !(0.0..=f64::from(u32::MAX)).contains(&rows) { return ps_err("rangecheck", "CCITTFaxDecode"); } - let encoding = if k < 0.0 { - EncodingMode::Group4 + let k_val = if k < 0.0 { + -1 } else if k == 0.0 { - EncodingMode::Group3_1D + 0 } else { - EncodingMode::Group3_2D { k: k.min(f64::from(u32::MAX)) as u32 } + k.min(f64::from(i64::MAX)) as i64 }; - Ok(DecodeSettings { - columns: columns as u32, - rows: rows as u32, + Ok(CcittParams { + k: k_val, + columns: columns as i64, + rows: rows as i64, end_of_block: flag("EndOfBlock", true), end_of_line: flag("EndOfLine", false), - rows_are_byte_aligned: flag("EncodedByteAlign", false), - encoding, - invert_black: flag("BlackIs1", false), + encoded_byte_align: flag("EncodedByteAlign", false), + black_is_1: flag("BlackIs1", false), }) } diff --git a/crates/eps/src/import/data/ops.rs b/crates/eps/src/import/data/ops.rs index 04e5431d30..fef595a924 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -893,12 +893,15 @@ impl Interp<'_> { let mask = self.alpha_mask(&alpha, img.w, img.h, xf); return self.add_image(blob, img.w, img.h, xf, mask); } - let Some(rgba) = image::RgbaImage::from_raw(img.w, img.h, img.rgba) else { return Ok(()) }; - let mut png = vec![]; - if rgba.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).is_err() { + let Ok(rgba) = + craft_image_codecs::Image::from_raw(img.w, img.h, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, img.rgba) + else { + return Ok(()); + }; + let Ok(png) = craft_image_codecs::encode(&rgba, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) else { self.out.warn("an image that couldn't be read was left out"); return Ok(()); - } + }; self.add_image(ImageBlob::new("image/png", png), img.w, img.h, xf, None) } @@ -919,8 +922,10 @@ impl Interp<'_> { if alpha.iter().all(|v| *v == 255) { return None; } - let mut png = Vec::new(); - image::GrayImage::from_raw(w, h, alpha.to_vec())?.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).ok()?; + let raw = + craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, alpha.to_vec()) + .ok()?; + let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); self.out.doc.images.entry(key.clone()).or_insert(blob); diff --git a/crates/eps/src/import/native.rs b/crates/eps/src/import/native.rs index 5acaba34a4..2075088367 100644 --- a/crates/eps/src/import/native.rs +++ b/crates/eps/src/import/native.rs @@ -168,11 +168,15 @@ mod tests { } let rect = vector.artboards[0].rect; let source = vectorcraft_render::Renderer::new().render_region(&vector, rect, 1.6, true); - let mut png = Vec::new(); - image::RgbaImage::from_raw(source.width, source.height, source.to_straight()) - .unwrap() - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + let raw = craft_image_codecs::Image::from_raw( + source.width, + source.height, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + source.to_straight(), + ) + .unwrap(); + let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); let mut page = Document::new(1000.0, 500.0); @@ -236,11 +240,15 @@ mod tests { vector.insert(Some(layer), usize::MAX, n).unwrap(); let rect = vector.artboards[0].rect; let source = vectorcraft_render::Renderer::new().render_region(&vector, rect, 1.0, true); - let mut png = Vec::new(); - image::RgbaImage::from_raw(source.width, source.height, source.to_straight()) - .unwrap() - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + let raw = craft_image_codecs::Image::from_raw( + source.width, + source.height, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + source.to_straight(), + ) + .unwrap(); + let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); let mut page = Document::new(width, height); diff --git a/crates/eps/src/import/preview.rs b/crates/eps/src/import/preview.rs index d4b4efb131..74e977e93a 100644 --- a/crates/eps/src/import/preview.rs +++ b/crates/eps/src/import/preview.rs @@ -32,12 +32,11 @@ pub(super) fn preview(bytes: &[u8], ps: &[u8], frame: Rect) -> Option { const MAX_PREVIEW_PIXELS: u64 = 1 << 26; fn tiff_rgba(tiff: &[u8]) -> Option { - let size = image::ImageReader::with_format(std::io::Cursor::new(tiff), image::ImageFormat::Tiff).into_dimensions(); - if size.is_ok_and(|(w, h)| u64::from(w) * u64::from(h) > MAX_PREVIEW_PIXELS) { - return None; - } - match image::load_from_memory_with_format(tiff, image::ImageFormat::Tiff) { - Ok(img) => Some(img.to_rgba8()), + let mut opts = craft_image_codecs::DecodeOptions::default(); + opts.limits.max_pixels = MAX_PREVIEW_PIXELS; + match craft_image_codecs::decode_as_with(craft_image_codecs::Format::Tiff, tiff, &opts) { + Ok(img) => image::RgbaImage::from_raw(img.width(), img.height(), img.to_rgba8()), + Err(craft_image_codecs::CodecError::LimitExceeded(_)) => None, Err(_) => crate::tiff::palette_rgba(tiff), } } @@ -48,8 +47,9 @@ fn image_doc(img: image::RgbaImage, frame: Rect) -> Option { if w == 0 || h == 0 { return None; } - let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).ok()?; + let raw = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, img.into_raw()) + .ok()?; + let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; let mut doc = Document::new(frame.width(), frame.height()); let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); diff --git a/crates/eps/src/import/tests.rs b/crates/eps/src/import/tests.rs index 4709a3c5bf..3b1f9cc939 100644 --- a/crates/eps/src/import/tests.rs +++ b/crates/eps/src/import/tests.rs @@ -598,7 +598,24 @@ fn images_and_image_masks() { let NodeKind::Image(im) = &o[0].kind else { panic!("{:?} {:?}", o, r.warnings) }; assert_eq!((im.width, im.height), (2, 2)); assert!(near(bounds(&o[0]), Rect::new(10.0, 70.0, 30.0, 90.0)), "{:?}", bounds(&o[0])); - let png = image::load_from_memory(&r.document.images[&im.key].bytes).unwrap().to_rgba8(); + let png = craft_image_codecs::decode(&r.document.images[&im.key].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!(png.get_pixel(0, 0).0, [255, 0, 0, 255]); assert_eq!(png.get_pixel(1, 1).0, [255, 255, 255, 255]); // The dictionary form through ASCII85 and run-length filters, grey with a decode array. @@ -608,12 +625,46 @@ fn images_and_image_masks() { << /ImageType 1 /Width 2 /Height 1 /BitsPerComponent 8 /Decode [1 0] /ImageMatrix [2 0 0 1 0 0] /DataSource src >> image\n{rl}" )); let NodeKind::Image(im) = &objects(&r.document)[0].kind else { panic!("{:?}", r.warnings) }; - let png = image::load_from_memory(&r.document.images[&im.key].bytes).unwrap().to_rgba8(); + let png = craft_image_codecs::decode(&r.document.images[&im.key].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!((png.get_pixel(0, 0).0, png.get_pixel(1, 0).0), ([255, 255, 255, 255], [0, 0, 0, 255])); // An image mask paints the current colour where its bits say. let r = read("1 0 0 setrgbcolor 8 1 true [8 0 0 1 0 0] imagemask"); let NodeKind::Image(im) = &objects(&r.document)[0].kind else { panic!() }; - let png = image::load_from_memory(&r.document.images[&im.key].bytes).unwrap().to_rgba8(); + let png = craft_image_codecs::decode(&r.document.images[&im.key].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!((png.get_pixel(0, 0).0, png.get_pixel(7, 0).0), ([255, 0, 0, 255], [255, 0, 0, 0])); } @@ -784,7 +835,41 @@ fn rich_doc() -> Document { *p = image::Rgba(if x < 4 { [0, 0, 255, 255] } else { [255, 200, 0, 255] }); } let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); d.images.insert("pic".into(), ImageBlob::new("image/png", png)); let im = ImageObject { key: "pic".into(), @@ -1415,7 +1500,24 @@ fn a_palette_preview_with_alpha_is_placed() { let NodeKind::Image(im) = &o[0].kind else { panic!("{:?}", o[0].kind) }; assert_eq!((im.width, im.height), (20, 10)); assert!(near(bounds(&o[0]), Rect::new(0.0, 0.0, 100.0, 100.0))); - let png = image::load_from_memory(&r.document.images[&im.key].bytes).unwrap().to_rgba8(); + let png = craft_image_codecs::decode(&r.document.images[&im.key].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); for (x, y) in [(0, 0), (1, 0), (2, 0), (19, 9), (7, 4), (3, 6)] { let [r, g, b] = [[255, 0, 0], [0, 128, 0], [0, 0, 255]][((x + y) % 3) as usize]; assert_eq!(png.get_pixel(x, y).0, [r, g, b, (x * 12) as u8], "({x}, {y}) {big} {per}"); diff --git a/crates/eps/src/import/tests_generators.rs b/crates/eps/src/import/tests_generators.rs index eb2d756fd8..270a1a3aa4 100644 --- a/crates/eps/src/import/tests_generators.rs +++ b/crates/eps/src/import/tests_generators.rs @@ -50,7 +50,24 @@ pub(super) fn pixel(d: &Document, x: u32, y: u32) -> [u8; 4] { _ => None, }) .unwrap(); - let img = image::load_from_memory(&d.images[&im].bytes).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&d.images[&im].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); img.get_pixel(x, y).0 } @@ -197,7 +214,24 @@ end"##, assert_eq!(of_kind(d, "Image").len(), 2); let im = all(d).into_iter().find(|n| matches!(&n.kind, NodeKind::Image(im) if im.width == 2)).unwrap(); let NodeKind::Image(im) = &im.kind else { panic!() }; - let img = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&d.images[&im.key].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); // Painted where the mask is 1, transparent where it is 0. assert_eq!([img.get_pixel(0, 0).0, img.get_pixel(1, 0).0], [[255, 0, 0, 255], [0, 255, 0, 0]]); assert_eq!([img.get_pixel(0, 1).0, img.get_pixel(1, 1).0], [[0, 0, 255, 0], [255, 255, 255, 255]]); diff --git a/crates/eps/src/import/tests_images.rs b/crates/eps/src/import/tests_images.rs index 193b81a233..91ed520d73 100644 --- a/crates/eps/src/import/tests_images.rs +++ b/crates/eps/src/import/tests_images.rs @@ -181,7 +181,24 @@ fn masked_cmyk_images_keep_their_inks_and_carry_the_mask_as_an_opacity_mask() { assert_eq!(inks(&r).data, [10, 20, 30, 40, 0, 102, 127, 8], "the inks as they were: {program}"); let n = first_image(&r); let mask = n.extras().mask.as_ref().expect("an opacity mask"); - let gray = image::load_from_memory(&blob(&r, &mask.art).bytes).unwrap().to_luma8(); + let gray = craft_image_codecs::decode(&blob(&r, &mask.art).bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_luma8(); assert_eq!(gray.into_raw(), alpha, "the mask's values: {program}"); assert_eq!(n.geometric_bounds(), mask.art.geometric_bounds(), "the mask covers the image"); } @@ -553,8 +570,9 @@ fn the_data_of_an_image_too_large_to_read_is_skipped() { /// allocates for them. #[test] fn a_jpeg_with_a_huge_header_is_refused_before_it_is_decoded() { - let mut jpeg = vec![]; - image::codecs::jpeg::JpegEncoder::new(&mut jpeg).encode(&[128; 64], 8, 8, image::ExtendedColorType::L8).unwrap(); + let cimg = craft_image_codecs::Image::from_raw(8, 8, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, vec![128; 64]) + .unwrap(); + let mut jpeg = craft_image_codecs::encode(&cimg, craft_image_codecs::Format::Jpeg, &craft_image_codecs::EncodeOptions::default()).unwrap(); // The frame header (marker, length, precision, height, width) now says 65535 × 65535. let sof = jpeg.windows(2).position(|w| w == [0xFF, 0xC0]).unwrap(); jpeg[sof + 5..sof + 9].fill(0xFF); diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 738f02d857..fb0f744988 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -620,7 +620,41 @@ fn top_level_placed_file_replacement_keeps_page_image_data() { let mut page = pdf_part(10.0, 86.0); let pixels = image::RgbaImage::from_pixel(4, 4, image::Rgba([0, 255, 255, 255])); let mut png = Vec::new(); - pixels.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (pixels).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); let expected = blob.bytes.clone(); @@ -1289,7 +1323,24 @@ fn an_ai_file_with_an_image_past_2_25_pixels_keeps_its_layers() { let png = &d.images[&im.key].bytes; // Bit depth 1, colour type 0 (gray). assert_eq!(png.get(24..26), Some([1, 0].as_slice())); - let gray = image::load_from_memory(png).unwrap().to_luma8(); + let gray = craft_image_codecs::decode(png) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_luma8(); assert_eq!((gray.get_pixel(0, 0)[0], gray.get_pixel(1, 0)[0], gray.get_pixel(5999, 5999)[0]), (0, 255, 255)); assert!(warnings.iter().all(|w| !w.contains("image")), "{warnings:?}"); } @@ -1317,7 +1368,24 @@ fn an_ai_image_past_the_target_size_is_reduced_and_keeps_the_layers() { (full.x0 - 50.0).abs() < 1e-9 && (full.x1 - 67.0).abs() < 1e-9 && (full.y0 - 86.0).abs() < 1e-9 && (full.y1 - 99.0).abs() < 1e-9, "{full:?}" ); - let gray = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_luma8(); + let gray = craft_image_codecs::decode(&d.images[&im.key].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_luma8(); // Steps of 4: blocks of rows 0–11 are half white rows, the last block row 12 alone; blocks of // columns 0–3 and 8–11 have 3 white columns of 4, and the last block column 16 alone. let rows: Vec> = (0..4).map(|y| (0..5).map(|x| gray.get_pixel(x, y)[0]).collect()).collect(); diff --git a/crates/eps/src/legacy_ai.rs b/crates/eps/src/legacy_ai.rs index 7e38b5ba51..4f73267647 100644 --- a/crates/eps/src/legacy_ai.rs +++ b/crates/eps/src/legacy_ai.rs @@ -174,10 +174,9 @@ pub fn writes_image_mask(doc: &Document, n: &Node) -> bool { let NodeKind::Image(im) = &n.kind else { return false }; // The size from the file's header, before any pixels are decoded. let fits = |bytes: &[u8]| { - image::ImageReader::new(std::io::Cursor::new(bytes)) - .with_guessed_format() + craft_image_codecs::probe_size(bytes) .ok() - .and_then(|r| r.into_dimensions().ok()) + .or_else(|| craft_image_codecs::decode(bytes).ok().map(|i| i.dimensions())) .is_some_and(|(w, h)| w > 0 && h > 0 && u64::from(w) * u64::from(h) <= MAX_IMAGE_PIXELS) }; matches!(n.extras().colorize.as_deref(), Some(Paint::Solid { .. })) diff --git a/crates/eps/src/legacy_ai/tests.rs b/crates/eps/src/legacy_ai/tests.rs index 663e21bec6..3dd4dd026b 100644 --- a/crates/eps/src/legacy_ai/tests.rs +++ b/crates/eps/src/legacy_ai/tests.rs @@ -58,7 +58,41 @@ fn sample() -> Document { doc.insert(Some(front), usize::MAX, ellipse).unwrap(); let mut png = vec![]; let img = image::RgbaImage::from_raw(2, 1, vec![255, 0, 0, 255, 0, 0, 255, 255]).unwrap(); - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); doc.images.insert(key.clone(), blob); @@ -507,11 +541,15 @@ fn writes_the_documented_operators() { #[test] fn a_rotated_image_keeps_its_place() { let mut doc = Document::new(200.0, 100.0); - let mut png = vec![]; - image::RgbaImage::from_raw(2, 1, vec![255, 0, 0, 255, 0, 0, 255, 255]) - .unwrap() - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + let img = craft_image_codecs::Image::from_raw( + 2, + 1, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + vec![255, 0, 0, 255, 0, 0, 255, 255], + ) + .unwrap(); + let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); doc.images.insert(key.clone(), blob); @@ -545,9 +583,41 @@ fn a_rotated_image_keeps_its_place() { /// A 16 × 16 RGB image of `doc` filling `r`. fn picture(doc: &mut Document, r: Rect) -> Node { let mut png = vec![]; - image::RgbaImage::from_fn(16, 16, |u, v| image::Rgba([(u * 16) as u8, (v * 16) as u8, 128, 255])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_fn(16, 16, |u, v| image::Rgba([(u * 16) as u8, (v * 16) as u8, 128, 255]))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); doc.images.insert(key.clone(), blob); @@ -666,9 +736,42 @@ fn the_pieces_of_a_warped_image_are_written_as_the_parts_they_show() { // GUARDS: each of a warped image's 200 pieces was written with all of the image's samples. let mut doc = Document::new(200.0, 160.0); let mut png = vec![]; - image::RgbaImage::from_fn(64, 64, |x, y| image::Rgba([(x * 4) as u8, (y * 4) as u8, ((x * 7 + y * 13) % 256) as u8, 255])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = + (image::RgbaImage::from_fn(64, 64, |x, y| image::Rgba([(x * 4) as u8, (y * 4) as u8, ((x * 7 + y * 13) % 256) as u8, 255]))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); doc.images.insert(key.clone(), blob); @@ -725,7 +828,41 @@ fn empty_images_get_the_size_note_and_undecodable_ones_the_decode_note() { /// at (`x`, `y`). fn colorized_image(doc: &mut Document, (w, h): (u32, u32), gray: Vec, paint: &Paint, (x, y): (f64, f64)) -> Node { let mut png = vec![]; - image::GrayImage::from_raw(w, h, gray).unwrap().write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::GrayImage::from_raw(w, h, gray).unwrap()).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); doc.images.insert(key.clone(), blob); diff --git a/crates/eps/src/legacy_ai/writer.rs b/crates/eps/src/legacy_ai/writer.rs index 0b41c3defa..97b515bbf9 100644 --- a/crates/eps/src/legacy_ai/writer.rs +++ b/crates/eps/src/legacy_ai/writer.rs @@ -1140,7 +1140,11 @@ impl<'a> Writer<'a> { { return img.clone(); } - let img = image::load_from_memory(&blob.bytes).ok().map(Arc::new); + let img = craft_image_codecs::decode(&blob.bytes) + .ok() + .and_then(|i| image::RgbaImage::from_raw(i.width(), i.height(), i.to_rgba8())) + .map(image::DynamicImage::ImageRgba8) + .map(Arc::new); self.last_image = Some((blob.clone(), img.clone())); img } diff --git a/crates/eps/src/scene.rs b/crates/eps/src/scene.rs index 299d130f7d..30a8101fc0 100644 --- a/crates/eps/src/scene.rs +++ b/crates/eps/src/scene.rs @@ -1629,7 +1629,7 @@ impl<'a> Scene<'a> { /// Image `blob` as RGBA pixels; `None` (with a warning) when it can't be written. fn decode_image(&mut self, blob: Option<&ImageBlob>) -> Option { - let Some(img) = blob.and_then(|blob| image::load_from_memory(&blob.bytes).ok()) else { + let Some(img) = blob.and_then(|blob| craft_image_codecs::decode(&blob.bytes).ok()) else { self.warn(UNDECODED); return None; }; @@ -1637,7 +1637,7 @@ impl<'a> Scene<'a> { self.warn(LARGE_IMAGE); return None; } - Some(img.to_rgba8()) + image::RgbaImage::from_raw(img.width(), img.height(), img.to_rgba8()) } /// Draw the image of `codes[i]` on the unit square mapped by `place`. Its operators go in when diff --git a/crates/eps/src/tests.rs b/crates/eps/src/tests.rs index 92971cee01..66ec6b0f59 100644 --- a/crates/eps/src/tests.rs +++ b/crates/eps/src/tests.rs @@ -803,7 +803,41 @@ fn png_doc() -> Document { /// A 200 × 200 pt document holding `img` as a PNG, its pixels `scale` points wide, at (10, 10). fn image_doc(img: &image::RgbaImage, scale: f64) -> Document { let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let mut d = Document::new(200.0, 200.0); d.images.insert("pic".into(), ImageBlob::new("image/png", png)); let im = ImageObject { @@ -934,9 +968,41 @@ fn colorized_doc(gray: Vec, paint: Option) -> Document { let mut d = Document::new(200.0, 200.0); d.swatches.push(Swatch { name: "Ink".into(), paint: Paint::solid(Color::cmyk(0.0, 1.0, 1.0, 0.0)), global: true, spot: true }); let mut png = Vec::new(); - image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(gray.len() as u32, 1, gray).unwrap()) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(gray.len() as u32, 1, gray).unwrap())).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); d.images.insert("gray".into(), ImageBlob::png(png)); let im = ImageObject { key: "gray".into(), @@ -1138,7 +1204,27 @@ fn noise(w: u32, h: u32) -> image::RgbaImage { fn imported_images(bytes: &[u8]) -> Vec> { fn walk(n: &Node, d: &Document, out: &mut Vec>) { if let NodeKind::Image(im) = &n.kind { - out.push(image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8().into_raw()); + out.push( + craft_image_codecs::decode(&d.images[&im.key].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() + .into_raw(), + ); } for c in n.children().into_iter().flatten() { walk(c, d, out); @@ -1551,7 +1637,24 @@ fn a_tiff_preview_sits_behind_the_binary_header() { assert_eq!(unpack(&[strip, &[128]].concat()), [0b1000_0000, 0b1010_0000]); continue; } - let img = image::load_from_memory_with_format(tiff, image::ImageFormat::Tiff).unwrap().to_rgba8(); + let img = craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, tiff) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!(img.dimensions(), (3, 2)); let expect: [u8; 4] = if transparent { [0, 0, 0, 0] } else { [255; 4] }; assert_eq!(img.get_pixel(2, 0).0, expect, "transparent, or on white"); @@ -1571,7 +1674,28 @@ fn the_native_document_and_thumbnail_come_back() { let out = export(&d, &o, Some(&preview()), Some(&preview())).unwrap(); assert_eq!(super::native(&out.bytes).as_deref(), Some(&native[..])); let png = super::thumbnail(&out.bytes).unwrap(); - assert_eq!(image::load_from_memory(&png).unwrap().to_rgba8().dimensions(), (3, 2)); + assert_eq!( + craft_image_codecs::decode(&png) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() + .dimensions(), + (3, 2) + ); let ps = text(&out); checked_page(&ps); assert!(ps.find("%VectorCraft_BeginData: thumbnail").unwrap() < ps.find("%%BeginProlog").unwrap()); diff --git a/crates/eps/src/tiff.rs b/crates/eps/src/tiff.rs index 4ee3b53d5b..e1c3d7431e 100644 --- a/crates/eps/src/tiff.rs +++ b/crates/eps/src/tiff.rs @@ -46,10 +46,15 @@ pub(crate) fn encode(img: &Raster, bw: bool, alpha: bool) -> Result, Str /// `img` as a PNG. pub(crate) fn png(img: &Raster) -> Result, String> { - let rgba = image::RgbaImage::from_raw(img.width, img.height, img.rgba.clone()).ok_or("the thumbnail image is malformed")?; - let mut out = vec![]; - rgba.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).map_err(|e| e.to_string())?; - Ok(out) + let raw = craft_image_codecs::Image::from_raw( + img.width, + img.height, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + img.rgba.clone(), + ) + .map_err(|_| "the thumbnail image is malformed".to_string())?; + craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).map_err(|e| e.to_string()) } /// Most pixels a palette preview may have. diff --git a/crates/mcp/Cargo.toml b/crates/mcp/Cargo.toml index 30cb6aef0a..4a74c6bdfb 100644 --- a/crates/mcp/Cargo.toml +++ b/crates/mcp/Cargo.toml @@ -26,6 +26,7 @@ serde_json = { workspace = true } log = { workspace = true } image = { workspace = true } +craft-image-codecs = { workspace = true } [dev-dependencies] vectorcraft-testkit = { workspace = true } diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index beda6d8ade..cd31a571fe 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -497,11 +497,16 @@ fn scaled_down_pictures_keep_the_color_beside_clear_pixels() { struct Striped; impl Backend for Striped { fn call(&mut self, method: &str, _: Value) -> Result { - let mut png = std::io::Cursor::new(Vec::new()); - image::RgbaImage::from_fn(64, 4, |x, _| if x % 2 == 0 { image::Rgba([200, 30, 30, 255]) } else { image::Rgba([0, 0, 0, 0]) }) - .write_to(&mut png, image::ImageFormat::Png) + let mut data = Vec::with_capacity(64 * 4 * 4); + for _ in 0..4 { + for x in 0..64 { + data.extend_from_slice(&if x % 2 == 0 { [200, 30, 30, 255] } else { [0, 0, 0, 0] }); + } + } + let raw = craft_image_codecs::Image::from_raw(64, 4, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, data) .unwrap(); - let png = vectorcraft_format::base64_encode(png.get_ref()); + let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); + let png = vectorcraft_format::base64_encode(&png); Ok(match method { "document.inspect" => json!({"artboards": [{"width": 64, "height": 4}]}), _ => json!({"pngBase64": png, "width": 64, "height": 4}), @@ -521,7 +526,8 @@ fn scaled_down_pictures_keep_the_color_beside_clear_pixels() { let r = call(&mut s, id, tool, args); let data = r["content"].as_array().unwrap().iter().find(|c| c["type"] == "image").unwrap_or_else(|| panic!("{tool}: {r}"))["data"].as_str().unwrap(); - let img = image::load_from_memory(&vectorcraft_format::base64_decode(data).unwrap()).unwrap().into_rgba8(); + let decoded = craft_image_codecs::decode(&vectorcraft_format::base64_decode(data).unwrap()).unwrap(); + let img = image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8()).unwrap(); assert_eq!(img.dimensions(), (16, 1), "{tool}"); assert!(img.pixels().all(|p| p.0 == [200, 30, 30, 128]), "{tool}: {:?}", img.get_pixel(0, 0)); } @@ -535,12 +541,16 @@ fn screenshot_and_render_preview_draw_the_trace_view_with_trace_views() { let dir = TempFolder::new("trace-views"); let mut s = server(); let png = dir.file("trace-views.png"); - image::RgbImage::from_fn(100, 100, |x, y| { - let (dx, dy) = (f64::from(x) + 0.5 - 50.0, f64::from(y) + 0.5 - 50.0); - if dx * dx + dy * dy <= 900.0 { image::Rgb([0, 0, 0]) } else { image::Rgb([170, 210, 255]) } - }) - .save(&png) - .unwrap(); + let mut rgb = Vec::with_capacity(100 * 100 * 3); + for y in 0..100 { + for x in 0..100 { + let (dx, dy) = (f64::from(x) + 0.5 - 50.0, f64::from(y) + 0.5 - 50.0); + rgb.extend_from_slice(&if dx * dx + dy * dy <= 900.0 { [0, 0, 0] } else { [170, 210, 255] }); + } + } + let raw = craft_image_codecs::Image::from_raw(100, 100, craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, rgb).unwrap(); + std::fs::write(&png, craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap()) + .unwrap(); let ok = |s: &mut Server, id: u64, name: &str, args: Value| { let r = call(s, id, name, args); assert_eq!(r["isError"], false, "{name}: {r}"); @@ -551,7 +561,8 @@ fn screenshot_and_render_preview_draw_the_trace_view_with_trace_views() { ok(&mut s, 3, "run_command", json!({"command": "imageTrace.make", "params": {"params": {"ignoreWhite": true}}})); let pixels = |r: &Value| { let data = r["content"].as_array().unwrap().iter().find(|c| c["type"] == "image").unwrap()["data"].as_str().unwrap(); - image::load_from_memory(&vectorcraft_format::base64_decode(data).unwrap()).unwrap().to_rgba8() + let decoded = craft_image_codecs::decode(&vectorcraft_format::base64_decode(data).unwrap()).unwrap(); + image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8()).unwrap() }; let dark = |p: &image::Rgba| p[0] < 60 && p[1] < 60 && p[2] < 60; let white = |p: &image::Rgba| p[0] > 245 && p[1] > 245 && p[2] > 245; diff --git a/crates/mcp/src/tests/conventions.rs b/crates/mcp/src/tests/conventions.rs index 3618f9214f..9020370c26 100644 --- a/crates/mcp/src/tests/conventions.rs +++ b/crates/mcp/src/tests/conventions.rs @@ -145,7 +145,7 @@ fn conventions_commands_batch_and_bounded_preview() { let r = call(&mut s, "render_preview", json!({"max_side":64})); assert_eq!(r["isError"], false, "{r}"); let png = vectorcraft_format::base64_decode(r["content"][0]["data"].as_str().unwrap()).unwrap(); - let img = image::load_from_memory(&png).unwrap(); + let img = craft_image_codecs::decode(&png).unwrap(); assert!(img.width() <= 64 && img.height() <= 64); assert_eq!(before, call(&mut s, "doc_inspect", json!({}))); for max in [json!(0), json!(4097), json!("64")] { @@ -157,7 +157,7 @@ fn conventions_commands_batch_and_bounded_preview() { let r = call(&mut s, "render_preview", json!({"max_side":60,"artboard":1})); assert_eq!(r["isError"], false, "{r}"); let png = vectorcraft_format::base64_decode(r["content"][0]["data"].as_str().unwrap()).unwrap(); - let img = image::load_from_memory(&png).unwrap(); + let img = craft_image_codecs::decode(&png).unwrap(); assert_eq!((img.width(), img.height()), (60, 20)); for board in [json!(2), json!(-1), json!("1")] { assert_eq!(call(&mut s, "render_preview", json!({"artboard":board}))["isError"], true, "{board}"); @@ -180,7 +180,10 @@ fn render_preview_and_screenshot_match_a_png_export_on_white() { } let r = call(&mut s, "draw_path", json!({"points":[[10,75],[110,5],[115,30]],"closed":true,"fill":"#30a050"})); assert_eq!(r["isError"], false, "{r}"); - let pixels = |b64: &str| image::load_from_memory(&vectorcraft_format::base64_decode(b64).unwrap()).unwrap().to_rgba8(); + let pixels = |b64: &str| { + let decoded = craft_image_codecs::decode(&vectorcraft_format::base64_decode(b64).unwrap()).unwrap(); + image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8()).unwrap() + }; let export = payload(&call(&mut s, "run_command", json!({"command":"document.export","params":{"format":"png","background":"white"}}))); let export = pixels(export["dataBase64"].as_str().unwrap()); assert_eq!(export.dimensions(), (120, 80)); @@ -276,11 +279,15 @@ impl Backend for Window { /// image down to it and reports the capture's own size; without it the capture comes back as sent. #[test] fn window_captures_take_max_side() { - let mut capture = std::io::Cursor::new(Vec::new()); - image::RgbaImage::from_fn(1200, 800, |x, y| image::Rgba([(x % 256) as u8, (y % 256) as u8, 90, 255])) - .write_to(&mut capture, image::ImageFormat::Png) - .unwrap(); - let capture = capture.into_inner(); + let mut data = Vec::with_capacity(1200 * 800 * 4); + for y in 0..800 { + for x in 0..1200 { + data.extend_from_slice(&[(x % 256) as u8, (y % 256) as u8, 90, 255]); + } + } + let raw = + craft_image_codecs::Image::from_raw(1200, 800, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, data).unwrap(); + let capture = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); let mut s = Server::new(Box::new(Window(capture.clone()))); let image_of = |r: &Value| vectorcraft_format::base64_decode(r["content"][0]["data"].as_str().unwrap()).unwrap(); let info = |r: &Value| -> Value { serde_json::from_str(r["content"][1]["text"].as_str().unwrap()).unwrap() }; @@ -292,7 +299,7 @@ fn window_captures_take_max_side() { args["max_side"] = json!(300); let r = call(&mut s, name, args.clone()); assert_eq!(r["isError"], false, "{name}: {r}"); - let img = image::load_from_memory(&image_of(&r)).unwrap(); + let img = craft_image_codecs::decode(&image_of(&r)).unwrap(); assert_eq!((img.width(), img.height()), (300, 200), "{name}"); let i = info(&r); assert_eq!((i["width"].clone(), i["height"].clone()), (json!(300), json!(200)), "{name}: {i}"); diff --git a/crates/mcp/src/tests/exportas.rs b/crates/mcp/src/tests/exportas.rs index 4e41002bf0..a0220fc38b 100644 --- a/crates/mcp/src/tests/exportas.rs +++ b/crates/mcp/src/tests/exportas.rs @@ -100,7 +100,7 @@ fn raster_export_uses_document_resolution_unless_overridden() { params["format"] = json!("png"); let r = text(&call_tool(&mut h, "export", ¶ms)); let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); - assert_eq!(image::load_from_memory(&bytes).unwrap().to_rgba8().dimensions(), size, "{args}"); + assert_eq!(craft_image_codecs::decode(&bytes).unwrap().dimensions(), size, "{args}"); } } @@ -116,7 +116,8 @@ fn export_with_a_range_writes_one_file_per_artboard() { for (f, board) in files.iter().zip(["Artboard-1", "Artboard-3"]) { let p = f.as_str().unwrap(); assert!(p.ends_with(&format!("icon-{board}.png")), "{p}"); - let img = image::load_from_memory(&std::fs::read(p).unwrap()).unwrap().to_rgba8(); + let decoded = craft_image_codecs::decode(&std::fs::read(p).unwrap()).unwrap(); + let img = image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8()).unwrap(); assert_eq!(img.dimensions(), (100, 60), "144 ppi"); assert!(img.pixels().all(|px| px[3] == 255), "white background"); } diff --git a/crates/mcp/src/tools/dispatch.rs b/crates/mcp/src/tools/dispatch.rs index 8e514ac48d..76084bf3c3 100644 --- a/crates/mcp/src/tools/dispatch.rs +++ b/crates/mcp/src/tools/dispatch.rs @@ -447,7 +447,16 @@ fn render_preview(b: &mut dyn Backend, a: &Args) -> Result { // The render was asked for at most 4096 a side. let img = super::handlers::decode_png(&png, 8192).map_err(|e| format!("read preview: {e}"))?; let img = if img.width() > max || img.height() > max { fitted(img, max, max, Resample::Average) } else { img }; - let mut out = std::io::Cursor::new(Vec::new()); - img.write_to(&mut out, image::ImageFormat::Png).map_err(|e| format!("encode preview: {e}"))?; - Ok(image_result(out.get_ref(), json!({"width":img.width(),"height":img.height()}))) + let rgba = img.to_rgba8(); + let raw = craft_image_codecs::Image::from_raw( + rgba.width(), + rgba.height(), + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + rgba.into_raw(), + ) + .map_err(|e| format!("encode preview: {e}"))?; + let out = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map_err(|e| format!("encode preview: {e}"))?; + Ok(image_result(&out, json!({"width":img.width(),"height":img.height()}))) } diff --git a/crates/mcp/src/tools/handlers.rs b/crates/mcp/src/tools/handlers.rs index 5aefa20d31..717c641e19 100644 --- a/crates/mcp/src/tools/handlers.rs +++ b/crates/mcp/src/tools/handlers.rs @@ -499,14 +499,16 @@ const MAX_CAPTURE_SIDE: u32 = 16_384; /// `png` decoded, refused when a side is longer than `side` or the decode needs more than 256 MiB: /// the picture is the app's reply, and its header names the size it is decoded at. -pub(super) fn decode_png(png: &[u8], side: u32) -> Result { - let mut reader = image::ImageReader::with_format(std::io::Cursor::new(png), image::ImageFormat::Png); - let mut limits = image::Limits::default(); - limits.max_image_width = Some(side); - limits.max_image_height = Some(side); - limits.max_alloc = Some(256 << 20); - reader.limits(limits); - reader.decode() +pub(super) fn decode_png(png: &[u8], side: u32) -> Result { + let mut opts = craft_image_codecs::DecodeOptions::default(); + opts.limits.max_width = side; + opts.limits.max_height = side; + opts.limits.max_alloc = 256 << 20; + let img = craft_image_codecs::decode_as_with(craft_image_codecs::Format::Png, png, &opts).map_err(|e| e.to_string())?; + let (w, h) = img.dimensions(); + image::RgbaImage::from_raw(w, h, img.to_rgba8()) + .map(image::DynamicImage::ImageRgba8) + .ok_or_else(|| "decoded PNG buffer size mismatch".to_string()) } /// A window capture with `max_side`: scaled down when its longer side is larger, with its own size @@ -525,9 +527,17 @@ fn fit_capture(png: Vec, max: Option, info: &mut Value) -> Result ToolResult { @@ -546,9 +556,15 @@ mod decode_tests { #[test] fn a_picture_with_a_side_past_the_limit_is_not_decoded() { - let mut png = std::io::Cursor::new(Vec::new()); - image::RgbaImage::new(200, 10).write_to(&mut png, image::ImageFormat::Png).unwrap(); - let png = png.into_inner(); + let img = craft_image_codecs::Image::from_raw( + 200, + 10, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + vec![0; 200 * 10 * 4], + ) + .unwrap(); + let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); assert!(decode_png(&png, 100).is_err()); assert_eq!(decode_png(&png, 200).unwrap().width(), 200); } diff --git a/crates/metafile/Cargo.toml b/crates/metafile/Cargo.toml index 01b5d6434a..67942f9d1e 100644 --- a/crates/metafile/Cargo.toml +++ b/crates/metafile/Cargo.toml @@ -17,6 +17,7 @@ vectorcraft-brush = { workspace = true } vectorcraft-text = { workspace = true } kurbo = { workspace = true } image = { workspace = true } +craft-image-codecs = { workspace = true } [dev-dependencies] # The tests lay type out in the bundled fonts (the workspace leaves turning them on to the engine). diff --git a/crates/metafile/src/dib.rs b/crates/metafile/src/dib.rs index e5b3f5cfcc..1af030a819 100644 --- a/crates/metafile/src/dib.rs +++ b/crates/metafile/src/dib.rs @@ -60,10 +60,15 @@ impl Rgba { /// As PNG bytes. pub fn to_png(&self) -> Result, String> { - let img = image::RgbaImage::from_raw(self.width, self.height, self.pixels.clone()).ok_or("the image's pixels don't match its size")?; - let mut png = vec![]; - img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| e.to_string())?; - Ok(png) + let img = craft_image_codecs::Image::from_raw( + self.width, + self.height, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + self.pixels.clone(), + ) + .map_err(|_| "the image's pixels don't match its size".to_string())?; + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).map_err(|e| e.to_string()) } } @@ -203,13 +208,18 @@ pub(crate) fn decode(bmi: &[u8], bits: &[u8], alpha: Alpha, left: &mut u64) -> R // A PNG's compressed ICC profile and text chunks expand when its decoder is made, and // nothing here uses them: they are left out before the size is read and the pixels decoded. let bits = png_without_metadata(bits); - let (w, h) = image::ImageReader::new(Cursor::new(&*bits)).with_guessed_format().map_err(|_| bad())?.into_dimensions().map_err(|_| bad())?; - if w > MAX_READ_SIDE || h > MAX_READ_SIDE || u64::from(w) * u64::from(h) > MAX_READ_PIXELS { - return Err("a bitmap is too large to read".into()); - } + let mut opts = craft_image_codecs::DecodeOptions::default(); + opts.limits.max_width = MAX_READ_SIDE; + opts.limits.max_height = MAX_READ_SIDE; + opts.limits.max_pixels = MAX_READ_PIXELS.min(*left); + let img = match craft_image_codecs::decode_with(&bits, &opts) { + Ok(img) => img, + Err(craft_image_codecs::CodecError::LimitExceeded(_)) => return Err("a bitmap is too large to read".into()), + Err(_) => return Err(bad()), + }; + let (w, h) = img.dimensions(); charge(w, h, left)?; - let img = image::load_from_memory(&bits).map_err(|_| bad())?.to_rgba8(); - return Ok(Rgba { width: w, height: h, pixels: img.into_raw() }); + return Ok(Rgba { width: w, height: h, pixels: img.to_rgba8() }); } if compression != BI_RGB && compression != BI_BITFIELDS { return Err("compressed (RLE) bitmaps can't be read yet".into()); @@ -327,16 +337,16 @@ mod tests { #[test] fn a_pngs_compressed_metadata_is_left_out_before_it_is_decoded() { - use image::ImageEncoder; - let mut png = vec![]; - let mut encoder = image::codecs::png::PngEncoder::new(&mut png); - encoder.set_icc_profile(vec![0; 1 << 20]).unwrap(); - encoder.write_image(&[10, 20, 30], 1, 1, image::ExtendedColorType::Rgb8).unwrap(); + let raw = + craft_image_codecs::Image::from_raw(1, 1, craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, vec![10, 20, 30]) + .unwrap() + .with_icc(Some(vec![0; 1 << 20])); + let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); assert!(png.windows(4).any(|w| w == b"iCCP")); let stripped = png_without_metadata(&png); assert!(!stripped.windows(4).any(|w| w == b"iCCP") && stripped.len() < png.len()); - let img = image::load_from_memory(&stripped).unwrap().to_rgba8(); - assert_eq!(img.get_pixel(0, 0).0, [10, 20, 30, 255]); + let img = craft_image_codecs::decode(&stripped).unwrap(); + assert_eq!(&img.to_rgba8()[..4], &[10, 20, 30, 255]); // Not a PNG, or a PNG cut short: unchanged. assert_eq!(&*png_without_metadata(b"BM...."), b"BM...."); assert_eq!(&*png_without_metadata(&png[..png.len() - 3]), &png[..png.len() - 3]); diff --git a/crates/metafile/src/import/pict.rs b/crates/metafile/src/import/pict.rs index a9b4cae9da..e4b9e3047c 100644 --- a/crates/metafile/src/import/pict.rs +++ b/crates/metafile/src/import/pict.rs @@ -1097,14 +1097,18 @@ impl Pict { /// A JPEG stream's pixels, taken from the file's pixel budget. fn jpeg(&mut self, data: &[u8]) -> Result { - let reader = || image::ImageReader::with_format(Cursor::new(data), image::ImageFormat::Jpeg); - let (w, h) = reader().into_dimensions().map_err(|_| BAD_IMAGE)?; - if w > dib::MAX_READ_SIDE || h > dib::MAX_READ_SIDE || u64::from(w) * u64::from(h) > dib::MAX_READ_PIXELS { - return Err(TOO_MANY_PIXELS); - } + let mut opts = craft_image_codecs::DecodeOptions::default(); + opts.limits.max_width = dib::MAX_READ_SIDE; + opts.limits.max_height = dib::MAX_READ_SIDE; + opts.limits.max_pixels = dib::MAX_READ_PIXELS.min(self.p.pixels_left); + let img = match craft_image_codecs::decode_as_with(craft_image_codecs::Format::Jpeg, data, &opts) { + Ok(img) => img, + Err(craft_image_codecs::CodecError::LimitExceeded(_)) => return Err(TOO_MANY_PIXELS), + Err(_) => return Err(BAD_IMAGE), + }; + let (w, h) = img.dimensions(); dib::charge(w, h, &mut self.p.pixels_left).map_err(|_| TOO_MANY_PIXELS)?; - let img = reader().decode().map_err(|_| BAD_IMAGE)?.to_rgba8(); - Ok(Rgba { width: img.width(), height: img.height(), pixels: img.into_raw() }) + Ok(Rgba { width: w, height: h, pixels: img.to_rgba8() }) } } diff --git a/crates/metafile/src/scene.rs b/crates/metafile/src/scene.rs index 6a6fd0b61f..3e7f2024d5 100644 --- a/crates/metafile/src/scene.rs +++ b/crates/metafile/src/scene.rs @@ -490,8 +490,9 @@ impl<'a> Scene<'a> { } let blob = self.doc.image_blob(im).filter(|b| !b.bytes.is_empty()); let img = blob - .and_then(|b| image::load_from_memory(&b.bytes).ok()) - .map(|i| Rgba::fitted(i.to_rgba8())) + .and_then(|b| craft_image_codecs::decode(&b.bytes).ok()) + .and_then(|i| image::RgbaImage::from_raw(i.width(), i.height(), i.to_rgba8())) + .map(Rgba::fitted) .filter(|i| i.width > 0 && i.height > 0) .map(Arc::new); if img.is_none() { diff --git a/crates/metafile/src/tests.rs b/crates/metafile/src/tests.rs index ceb65d6fe2..9265aaaf03 100644 --- a/crates/metafile/src/tests.rs +++ b/crates/metafile/src/tests.rs @@ -43,10 +43,15 @@ pub(crate) fn blue() -> Paint { /// A `w` × `h` PNG of `rgba`. pub(crate) fn png(w: u32, h: u32, rgba: [u8; 4]) -> Vec { - let img = image::RgbaImage::from_pixel(w, h, image::Rgba(rgba)); - let mut out = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); - out + let img = craft_image_codecs::Image::from_raw( + w, + h, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + rgba.repeat((w * h) as usize), + ) + .unwrap(); + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap() } /// CRC-32 of a PNG chunk. @@ -64,8 +69,11 @@ pub(crate) fn crc32(data: &[u8]) -> u32 { /// A 1 × 1 PNG whose IHDR claims `w` × `h` (and whose CRC matches): its size reads from the header, /// but its pixel data no longer matches, so decoding it fails. pub(crate) fn png_claiming(w: u32, h: u32) -> Vec { - let mut png = vec![]; - image::GrayImage::new(1, 1).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let mut png = craft_image_codecs::encode( + &craft_image_codecs::Image::from_raw(1, 1, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, vec![0]).unwrap(), + craft_image_codecs::Format::Png, + ) + .unwrap(); png[16..20].copy_from_slice(&w.to_be_bytes()); png[20..24].copy_from_slice(&h.to_be_bytes()); let crc = crc32(&png[12..29]); diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index 1e0ec5671b..56ab9cb634 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -102,7 +102,8 @@ fn freeform_points_that_share_a_model_are_written_as_their_mix() { _ => None, }) .unwrap(); - let px = image::load_from_memory(&back.document.images[&im.key].bytes).unwrap().to_rgba8(); + let decoded = craft_image_codecs::decode(&back.document.images[&im.key].bytes).unwrap(); + let px = image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8()).unwrap(); px.get_pixel(px.width() / 2, px.height() / 2).0 }; let near = |got: [u8; 4], want: [u8; 4]| got.iter().zip(want).all(|(g, w)| g.abs_diff(w) <= 6); @@ -144,7 +145,8 @@ fn dashes_gradients_and_images_round_trip_through_emf() { assert_eq!(im.height, 2); let placed = im.xf.transform_rect_bbox(Rect::new(0.0, 0.0, 4.0, 2.0)); assert!(near(placed, Rect::new(100.0, 10.0, 120.0, 20.0), 0.05), "{placed:?}"); - let px = image::load_from_memory(&back.document.images[&im.key].bytes).unwrap().to_rgba8(); + let decoded = craft_image_codecs::decode(&back.document.images[&im.key].bytes).unwrap(); + let px = image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8()).unwrap(); assert_eq!(px.get_pixel(0, 0).0, [0, 200, 0, 255]); } diff --git a/crates/metafile/src/tests/pict.rs b/crates/metafile/src/tests/pict.rs index 055e88c95b..0d8b48c939 100644 --- a/crates/metafile/src/tests/pict.rs +++ b/crates/metafile/src/tests/pict.rs @@ -87,7 +87,8 @@ fn images(d: &Document) -> Vec<(Node, image::RgbaImage)> { .into_iter() .filter_map(|n| match &n.kind { NodeKind::Image(im) => { - let png = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8(); + let decoded = craft_image_codecs::decode(&d.images[&im.key].bytes).unwrap(); + let png = image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8()).unwrap(); Some((n.clone(), png)) } _ => None, @@ -374,10 +375,15 @@ fn quicktime(ctype: &[u8; 4], matrix: [f64; 6], w: i16, h: i16, data: &[u8]) -> } fn red_jpeg() -> Vec { - let img = image::RgbImage::from_pixel(4, 2, image::Rgb([255, 0, 0])); - let mut out = std::io::Cursor::new(vec![]); - img.write_to(&mut out, image::ImageFormat::Jpeg).unwrap(); - out.into_inner() + let img = craft_image_codecs::Image::from_raw( + 4, + 2, + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U8, + [255u8, 0, 0].repeat(8), + ) + .unwrap(); + craft_image_codecs::encode(&img, craft_image_codecs::Format::Jpeg, &craft_image_codecs::EncodeOptions::default()).unwrap() } #[test] diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml index d59243eb75..ff97690e51 100644 --- a/crates/pdf/Cargo.toml +++ b/crates/pdf/Cargo.toml @@ -24,14 +24,13 @@ kurbo = { workspace = true } thiserror = { workspace = true } flate2 = { workspace = true, features = ["zlib-rs"] } image = { workspace = true } -# CMYK JPEGs (the image crate writes RGB and grey ones only). -jpeg-encoder = { workspace = true } +craft-image-codecs = { workspace = true } craft-pdf = { workspace = true } +craft-stream-codecs = { workspace = true } log = { workspace = true } chrono = { workspace = true } smallvec = "1" siphasher = "1" -weezl = "0.2" serde = { workspace = true } # The XMP packet that File Info is read from (file_info.rs). craft-xml = { workspace = true } diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs index 4ba361d29b..86a750b345 100644 --- a/crates/pdf/src/export.rs +++ b/crates/pdf/src/export.rs @@ -164,19 +164,21 @@ mod tests { #[test] fn a_16_bit_png_at_8_bits_keeps_its_color_type_and_icc_profile() { - use image::{ImageDecoder, ImageEncoder}; + use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image as CodecImage, SampleType}; let icc = vectorcraft_color::cms::icc_bytes(vectorcraft_color::cms::GRAY).unwrap().to_vec(); - let gray = image::DynamicImage::ImageLuma16(image::ImageBuffer::from_fn(4, 2, |x, y| image::Luma([x as u16 * 20000 + y as u16]))); - let mut png = vec![]; - let mut encoder = image::codecs::png::PngEncoder::new(&mut png); - encoder.set_icc_profile(icc.clone()).unwrap(); - gray.write_with_encoder(encoder).unwrap(); + let u16_samples: Vec = (0..2).flat_map(|y| (0..4).map(move |x| x as u16 * 20000 + y as u16)).collect(); + let raw_u16: Vec = u16_samples.iter().flat_map(|v| v.to_ne_bytes()).collect(); + let mut src = CodecImage::from_raw(4, 2, ChannelLayout::Gray, SampleType::U16, raw_u16).unwrap(); + src.icc = Some(icc.clone()); + let png = craft_image_codecs::encode(&src, Format::Png, &EncodeOptions::default()).unwrap(); assert!(png_16_bit(&png)); let out = png_8_bit(&png).unwrap(); assert!(!png_16_bit(&out)); - let mut decoder = image::codecs::png::PngDecoder::new(std::io::Cursor::new(out.as_slice())).unwrap(); - assert_eq!(decoder.icc_profile().unwrap(), Some(icc)); - assert_eq!(decoder.color_type(), image::ColorType::L8); - assert_eq!(image::DynamicImage::from_decoder(decoder).unwrap().to_luma8(), gray.to_luma8()); + let decoded = craft_image_codecs::decode_as_with(Format::Png, &out, &craft_image_codecs::Limits::default()).unwrap(); + assert_eq!(decoded.icc, Some(icc)); + assert_eq!(decoded.layout(), ChannelLayout::Gray); + assert_eq!(decoded.sample_type(), SampleType::U8); + let want: Vec = u16_samples.into_iter().map(|v| (v >> 8) as u8).collect(); + assert_eq!(decoded.data(), want); } } diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index 8110ce2db5..ad0582f9a4 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -296,23 +296,20 @@ pub(super) fn png_16_bit(bytes: &[u8]) -> bool { /// PNG `bytes` at 8 bits a sample: decoded, and encoded again as gray or RGB, with alpha when the /// source has it, and with the source's ICC profile. `None` when it can't be decoded. pub(super) fn png_8_bit(bytes: &[u8]) -> Option> { - use image::{ColorType, DynamicImage, ImageDecoder, ImageEncoder}; - let mut decoder = image::codecs::png::PngDecoder::new(std::io::Cursor::new(bytes)).ok()?; - let icc = decoder.icc_profile().ok().flatten(); - let img = DynamicImage::from_decoder(decoder).ok()?; - let img = match img.color() { - ColorType::L8 | ColorType::L16 => DynamicImage::ImageLuma8(img.into_luma8()), - ColorType::La8 | ColorType::La16 => DynamicImage::ImageLumaA8(img.into_luma_alpha8()), - ColorType::Rgb8 | ColorType::Rgb16 => DynamicImage::ImageRgb8(img.into_rgb8()), - _ => DynamicImage::ImageRgba8(img.into_rgba8()), + use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image as CodecImage, Limits, SampleType}; + let decoded = craft_image_codecs::decode_as_with(Format::Png, bytes, &Limits::default()).ok()?; + let (w, h) = decoded.dimensions(); + let icc = decoded.icc.clone(); + let (layout, data) = match (decoded.layout(), decoded.sample_type()) { + (l @ (ChannelLayout::Gray | ChannelLayout::GrayA | ChannelLayout::Rgb | ChannelLayout::Rgba), SampleType::U8) => (l, decoded.into_data()), + (l @ (ChannelLayout::Gray | ChannelLayout::GrayA | ChannelLayout::Rgb | ChannelLayout::Rgba), SampleType::U16) => { + let u8s: Vec = decoded.to_u16_samples()?.into_iter().map(|s| ((u32::from(s) * 255 + 32767) / 65535) as u8).collect(); + (l, u8s) + } + _ => return None, }; - let mut png = vec![]; - let mut encoder = image::codecs::png::PngEncoder::new(&mut png); - if let Some(icc) = icc { - encoder.set_icc_profile(icc).ok()?; - } - img.write_with_encoder(encoder).ok()?; - Some(png) + let out = CodecImage::from_raw(w, h, layout, SampleType::U8, data).ok()?.with_icc(icc); + craft_image_codecs::encode(&out, Format::Png, &EncodeOptions::default()).ok() } /// Image `blob` as it is: PNG, JPEG, GIF and WebP through the PDF writer (JPEG data unchanged), @@ -321,8 +318,8 @@ pub(super) fn png_8_bit(bytes: &[u8]) -> Option> { pub(super) fn embed(blob: &vectorcraft_doc::ImageBlob, interpolate: bool, sixteen_bit: bool) -> Option { // The header's size first: the writer's decoders allocate what it declares, and the encoded // bytes of an image that is far larger than any the app reads may be a few kilobytes. - let size = image::ImageReader::new(std::io::Cursor::new(blob.bytes.as_slice())).with_guessed_format().ok()?.into_dimensions(); - if size.is_ok_and(|(w, h)| u64::from(w) * u64::from(h) > crate::images::MAX_EMBED_PIXELS) { + let info = craft_image_codecs::probe(&blob.bytes).ok(); + if info.as_ref().is_some_and(|i| u64::from(i.width) * u64::from(i.height) > crate::images::MAX_EMBED_PIXELS) { return None; } let bytes = blob.bytes.as_ref().clone(); @@ -335,9 +332,9 @@ pub(super) fn embed(blob: &vectorcraft_doc::ImageBlob, interpolate: bool, sixtee _ => None, }; direct.or_else(|| { - let rgba = image::load_from_memory(&bytes).ok()?.to_rgba8(); - let (w, h) = rgba.dimensions(); - Some(Image::from_rgba8(rgba.into_raw(), w, h)) + let decoded = craft_image_codecs::decode(&bytes).ok()?; + let (w, h) = decoded.dimensions(); + Some(Image::from_rgba8(decoded.to_rgba8(), w, h)) }) } @@ -351,8 +348,10 @@ mod tests { #[test] fn an_image_whose_header_declares_far_more_pixels_than_the_app_reads_is_left_out() { // A real 8 × 8 PNG whose IHDR (width, height at 16..24) claims 65535 × 65535, with its CRC fixed. - let mut png = vec![]; - image::DynamicImage::ImageRgb8(image::RgbImage::new(8, 8)).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let img = + craft_image_codecs::Image::from_raw(8, 8, craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, vec![0; 8 * 8 * 3]) + .unwrap(); + let mut png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); png[16..24].copy_from_slice(&[0, 0, 0xFF, 0xFF, 0, 0, 0xFF, 0xFF]); let crc = !png[12..29].iter().fold(!0u32, |c, b| (0..8).fold(c ^ u32::from(*b), |c, _| if c & 1 == 1 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 })); @@ -386,8 +385,9 @@ mod tests { #[test] fn colorized_and_grid_masked_images_are_made_once_for_every_size_without_downsampling() { let gray = |pixels: Vec| { - let mut png = vec![]; - image::GrayImage::from_raw(2, 2, pixels).unwrap().write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let img = craft_image_codecs::Image::from_raw(2, 2, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, pixels) + .unwrap(); + let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); ImageBlob::png(png) }; let mut doc = Document::new(100.0, 100.0); diff --git a/crates/pdf/src/file_info.rs b/crates/pdf/src/file_info.rs index 908212aabe..930f7e4013 100644 --- a/crates/pdf/src/file_info.rs +++ b/crates/pdf/src/file_info.rs @@ -20,8 +20,7 @@ const XMP: &str = "http://ns.adobe.com/xap/1.0/"; // brand-ok: the XMP namespace pub(crate) const XMP_RIGHTS: &str = "http://ns.adobe.com/xap/1.0/rights/"; // brand-ok: the XMP namespace the files use const PDF: &str = "http://ns.adobe.com/pdf/1.3/"; // brand-ok: the XMP namespace the files use -const XMP_NAMESPACES: Canonical<'static> = - Canonical::new(&[("rdf", RDF), ("dc", DC), ("xmp", XMP), ("xmpRights", XMP_RIGHTS), ("pdf", PDF)]); +const XMP_NAMESPACES: Canonical<'static> = Canonical::new(&[("rdf", RDF), ("dc", DC), ("xmp", XMP), ("xmpRights", XMP_RIGHTS), ("pdf", PDF)]); /// The File Info fields a PDF gives, each `None` when the file gives none (or only blank text). #[derive(Clone, Debug, Default, PartialEq, Eq)] @@ -146,10 +145,7 @@ fn property(descriptions: &[&El], name: &str) -> Vec { fn items(p: &El) -> Vec { let array = p.elements().find(|c| matches!(c.name.as_str(), "rdf:Seq" | "rdf:Bag" | "rdf:Alt")); let mut values: Vec<(bool, String)> = match array { - Some(a) => a - .children("rdf:li") - .map(|li| (li.attr("xml:lang").is_some_and(|l| l.eq_ignore_ascii_case("x-default")), value_of(li))) - .collect(), + Some(a) => a.children("rdf:li").map(|li| (li.attr("xml:lang").is_some_and(|l| l.eq_ignore_ascii_case("x-default")), value_of(li))).collect(), None => vec![(false, value_of(p))], }; // A stable sort: the `x-default` item first, the others in their order. diff --git a/crates/pdf/src/images.rs b/crates/pdf/src/images.rs index d8b873364c..87db970405 100644 --- a/crates/pdf/src/images.rs +++ b/crates/pdf/src/images.rs @@ -14,12 +14,12 @@ //! kept carries the CMYK profile it is given ([`cmyk_icc`]), whether it is embedded as it is or //! written again; without one it is untagged, a JPEG's own `ICC_PROFILE` segments included. -use std::io::Cursor; use std::sync::Arc; +use craft_image_codecs::{ChannelLayout, Format, Limits as CodecLimits, SampleType}; use craft_pdf::write::backend as krilla; +use image::DynamicImage; use image::imageops::FilterType; -use image::{DynamicImage, ExtendedColorType, ImageDecoder, ImageFormat, ImageReader}; use krilla::image::{BitsPerComponent, CustomImage, Image, ImageColorspace}; use vectorcraft_doc::ImageBlob; @@ -310,23 +310,35 @@ fn resample_channels(img: DynamicImage, r: &Rule, (w, h): (u32, u32)) -> Dynamic /// can't be decoded is kept as it is. pub(crate) fn recode(bytes: &[u8], size: (f64, f64), c: &CompressionSettings, interpolate: bool, convert: Option<&Pixels>) -> Recoded { let keep = Recoded { image: None, warning: None }; - let Ok(reader) = ImageReader::new(Cursor::new(bytes)).with_guessed_format() else { return keep }; - let jpeg = reader.format() == Some(ImageFormat::Jpeg); - let Ok(mut decoder) = reader.into_decoder() else { return keep }; - // What the header declares is decoded within the image allowance, not whatever it asks for. - if decoder.set_limits(limits()).is_err() { - return keep; - } - let dims = decoder.dimensions(); - use ExtendedColorType as T; - let grey = matches!(decoder.original_color_type(), T::L1 | T::La1 | T::L2 | T::La2 | T::L4 | T::La4 | T::L8 | T::La8 | T::L16 | T::La16); + let Some(fmt) = craft_image_codecs::detect(bytes) else { return keep }; + let jpeg = fmt == Format::Jpeg; + let (dims, grey) = match fmt { + Format::Png => { + let Ok(dec) = craft_image_codecs::PngDecodeRows::new_streaming(bytes, &codec_limits()) else { return keep }; + let h = dec.header(); + ((h.width, h.height), matches!(h.layout, ChannelLayout::Gray | ChannelLayout::GrayA)) + } + Format::Jpeg => { + let Some(info) = craft_image_codecs::jpeg_info(bytes) else { return keep }; + ((info.width, info.height), matches!(info.layout, ChannelLayout::Gray | ChannelLayout::GrayA)) + } + Format::Tiff => { + let Ok(info) = craft_image_codecs::tiff_info(bytes) else { return keep }; + let Some(p) = info.pages.first() else { return keep }; + ((p.width, p.height), false) + } + _ => { + let Ok(dims) = craft_image_codecs::probe_size(bytes) else { return keep }; + (dims, false) + } + }; let (kind, pixels) = if grey { // Only the pixels tell monochrome images from greyscale ones: decoded unless both keep it. let (g, m) = (rule(c, Kind::Gray), rule(c, Kind::Mono)); if kept(&g, dims, size, jpeg) && kept(&m, dims, size, jpeg) && g.instead == m.instead { return Recoded { image: None, warning: g.instead }; } - let Ok(img) = DynamicImage::from_decoder(decoder) else { return keep }; + let Some(img) = decoded(bytes) else { return keep }; (if bilevel(&img) { Kind::Mono } else { Kind::Gray }, Some(img)) } else { (Kind::Color, None) @@ -405,7 +417,7 @@ pub(crate) fn recode_cmyk( let jpeg = jpeg_components(&blob.bytes).is_some(); let icc = icc.filter(|_| convert.is_none()); if jpeg && convert.is_none() && alpha.is_none() { - let dims = ImageReader::new(Cursor::new(blob.bytes.as_slice())).with_guessed_format().ok().and_then(|r| r.into_dimensions().ok()); + let dims = craft_image_codecs::probe(&blob.bytes).ok().map(|i| (i.width, i.height)); if let Some((w, h)) = dims.filter(|d| kept(&rule, *d, size, true)) { // The JPEG data as it is, tagged with `icc` rather than with its own segments; one // larger than [`MAX_EMBED_PIXELS`] is not written. @@ -467,17 +479,26 @@ fn resampled_inks(inks: Inks, alpha: Option>, r: &Rule, to: (u32, u32)) const MAX_DECODE: u64 = 512 << 20; /// The decoder limits of an image read here: [`MAX_DECODE`] bytes. -fn limits() -> image::Limits { - let mut l = image::Limits::default(); - l.max_alloc = Some(MAX_DECODE); - l +fn codec_limits() -> CodecLimits { + CodecLimits { max_alloc: Some(MAX_DECODE), ..CodecLimits::default() } } -/// `bytes` decoded within [`limits`]: an image whose header asks for more is not decoded. +/// `bytes` decoded within [`codec_limits`]: an image whose header asks for more is not decoded. fn decoded(bytes: &[u8]) -> Option { - let mut r = ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?; - r.limits(limits()); - r.decode().ok() + let opts = craft_image_codecs::DecodeOptions { limits: codec_limits(), ..Default::default() }; + let img = craft_image_codecs::decode_with(bytes, &opts).ok()?; + let (w, h) = img.dimensions(); + match (img.layout(), img.sample_type()) { + (ChannelLayout::Gray, SampleType::U8) => image::GrayImage::from_raw(w, h, img.into_data()).map(DynamicImage::ImageLuma8), + (ChannelLayout::GrayA, SampleType::U8) => image::GrayAlphaImage::from_raw(w, h, img.into_data()).map(DynamicImage::ImageLumaA8), + (ChannelLayout::Rgb, SampleType::U8) => image::RgbImage::from_raw(w, h, img.into_data()).map(DynamicImage::ImageRgb8), + (ChannelLayout::Rgba, SampleType::U8) => image::RgbaImage::from_raw(w, h, img.into_data()).map(DynamicImage::ImageRgba8), + (ChannelLayout::Gray, SampleType::U16) => image::ImageBuffer::from_raw(w, h, img.to_u16_samples()?).map(DynamicImage::ImageLuma16), + (ChannelLayout::GrayA, SampleType::U16) => image::ImageBuffer::from_raw(w, h, img.to_u16_samples()?).map(DynamicImage::ImageLumaA16), + (ChannelLayout::Rgb, SampleType::U16) => image::ImageBuffer::from_raw(w, h, img.to_u16_samples()?).map(DynamicImage::ImageRgb16), + (ChannelLayout::Rgba, SampleType::U16) => image::ImageBuffer::from_raw(w, h, img.to_u16_samples()?).map(DynamicImage::ImageRgba16), + _ => None, + } } /// The alpha an opacity mask whose art is greyscale image `blob` alone gives the image of @@ -490,8 +511,8 @@ pub(crate) fn mask_alpha(blob: &ImageBlob, width: u32, height: u32, clip: bool) } // The size from the header first: a mask of another size, or too large to hold as RGBA, is // not decoded at all. - let reader = ImageReader::new(Cursor::new(blob.bytes.as_slice())).with_guessed_format().ok()?; - if reader.into_dimensions().ok()? != (width, height) || u64::from(width) * u64::from(height) * 4 > MAX_DECODE { + let info = craft_image_codecs::probe(&blob.bytes).ok()?; + if (info.width, info.height) != (width, height) || u64::from(width) * u64::from(height) * 4 > MAX_DECODE { return None; } let img = decoded(&blob.bytes)?.into_rgba8(); @@ -506,18 +527,17 @@ pub(crate) fn mask_alpha(blob: &ImageBlob, width: u32, height: u32, clip: bool) /// `quality`, tagged with ICC profile `icc` when given. CMYK JPEGs hold Adobe's inverted samples, /// which the PDF writer's Decode array undoes. fn to_jpeg(samples: &[u8], space: ImageColorspace, width: u32, height: u32, quality: u8, interpolate: bool, icc: Option<&[u8]>) -> Option { - let mut out = Vec::new(); - match space { - ImageColorspace::Cmyk => { - let (w, h) = (u16::try_from(width).ok()?, u16::try_from(height).ok()?); - jpeg_encoder::Encoder::new(&mut out, quality).encode(samples, w, h, jpeg_encoder::ColorType::Cmyk).ok()?; - } - ImageColorspace::Rgb | ImageColorspace::Luma => { - let t = if space == ImageColorspace::Rgb { ExtendedColorType::Rgb8 } else { ExtendedColorType::L8 }; - image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, quality).encode(samples, width, height, t).ok()?; - } + let layout = match space { + ImageColorspace::Cmyk => craft_image_codecs::ChannelLayout::Cmyk, + ImageColorspace::Rgb => craft_image_codecs::ChannelLayout::Rgb, + ImageColorspace::Luma => craft_image_codecs::ChannelLayout::Gray, ImageColorspace::DeviceN => return None, - } + }; + let mut img = craft_image_codecs::Image::from_u8(width, height, layout, samples.to_vec()).ok()?; + img.icc = icc.map(|i| i.to_vec()); + let opts = + craft_image_codecs::EncodeOptions { jpeg_quality: quality.clamp(1, 100), embed_icc: false, embed_metadata: false, ..Default::default() }; + let out = craft_image_codecs::encode(&img, craft_image_codecs::Format::Jpeg, &opts).ok()?; Image::from_jpeg_with_icc(out.into(), icc.map(|i| i.to_vec().into()), interpolate).ok() } diff --git a/crates/pdf/src/import/builder.rs b/crates/pdf/src/import/builder.rs index 0b32054c7b..c73e97a5b3 100644 --- a/crates/pdf/src/import/builder.rs +++ b/crates/pdf/src/import/builder.rs @@ -747,8 +747,15 @@ impl<'p> Builder<'p> { self.opaque.insert(mkey); return None; }; - let mut png = Vec::new(); - image::GrayImage::from_raw(a.width, a.height, a.data)?.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).ok()?; + let raw = craft_image_codecs::Image::from_raw( + a.width, + a.height, + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U8, + a.data, + ) + .ok()?; + let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; let blob = ImageBlob::new("image/png", png); let k = blob.content_key(); self.images.insert(k.clone(), blob); diff --git a/crates/pdf/src/import/state.rs b/crates/pdf/src/import/state.rs index 12eb4498dc..ba871dcea2 100644 --- a/crates/pdf/src/import/state.rs +++ b/crates/pdf/src/import/state.rs @@ -329,17 +329,13 @@ pub(super) fn bounds(nodes: &[Arc]) -> Option { } pub(super) fn rgba_png(rgba: Vec, w: u32, h: u32) -> Option> { - let img = image::RgbaImage::from_raw(w, h, rgba)?; - let mut out = Vec::new(); - img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).ok()?; - Some(out) + let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba).ok()?; + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok() } pub(super) fn gray_png(gray: Vec, w: u32, h: u32) -> Option> { - let img = image::GrayImage::from_raw(w, h, gray)?; - let mut out = Vec::new(); - img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).ok()?; - Some(out) + let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, gray).ok()?; + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok() } pub(super) fn resize_alpha(a: &LumaData, w: u32, h: u32) -> Vec { diff --git a/crates/pdf/src/streams.rs b/crates/pdf/src/streams.rs index 8fb57198fe..3f99b8b82a 100644 --- a/crates/pdf/src/streams.rs +++ b/crates/pdf/src/streams.rs @@ -71,23 +71,14 @@ fn inflate(data: &[u8], max: usize) -> Option> { read(Box::new(flate2::read::ZlibDecoder::new(data))).or_else(|| read(Box::new(flate2::read::DeflateDecoder::new(data)))) } -/// `data` decoded from LZW, up to one byte past `max`. `early`: the code length grows one code +/// `data` decoded from LZW, up to `max`. `early`: the code length grows one code /// early (`EarlyChange`, 1 by default). fn lzw(data: &[u8], early: bool, max: usize) -> Option> { - use weezl::{BitOrder, LzwStatus, decode::Decoder}; - let mut decoder = if early { Decoder::with_tiff_size_switch(BitOrder::Msb, 8) } else { Decoder::new(BitOrder::Msb, 8) }; - let (mut out, mut chunk, mut input) = (vec![], vec![0; 1 << 16], data); - while out.len() <= max { - let r = decoder.decode_bytes(input, &mut chunk); - input = input.get(r.consumed_in..).unwrap_or_default(); - out.extend_from_slice(chunk.get(..r.consumed_out).unwrap_or_default()); - match r.status { - Ok(LzwStatus::Ok) => {} - Ok(LzwStatus::Done | LzwStatus::NoProgress) => break, - Err(_) => return (out.len() > max).then_some(out), - } + match craft_stream_codecs::lzw::decode(data, early, max) { + Ok(out) => Some(out), + Err(f) if matches!(f.error, craft_stream_codecs::CodecError::LimitExceeded(_)) => Some(vec![0u8; max.saturating_add(1)]), + Err(_) => None, } - Some(out) } /// `data` decoded from run-length encoding, up to one byte past `max`. diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 5e9796b9b4..b91f29344c 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -763,7 +763,41 @@ fn tiny_png() -> Vec { *p = image::Rgba([if x < 2 { 255 } else { 0 }, 0, 0, 255]); } let mut out = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); out } @@ -788,7 +822,24 @@ fn image_roundtrip() { assert_eq!((im.width, im.height), (4, 2)); assert!(close(l[0].geometric_bounds().unwrap(), Rect::new(20.0, 30.0, 60.0, 50.0), 0.01), "{:?}", l[0].geometric_bounds()); let blob = &out.images[&im.key]; - let decoded = image::load_from_memory(&blob.bytes).unwrap().to_rgba8(); + let decoded = craft_image_codecs::decode(&blob.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!(decoded.get_pixel(0, 0).0, [255, 0, 0, 255]); assert_eq!(decoded.get_pixel(3, 0).0, [0, 0, 0, 255]); } @@ -820,9 +871,42 @@ fn a_pixelated_image_asks_viewers_not_to_smooth_it() { /// A 4 × 2 red image encoded as `format`, cut short `keep` bytes past the first `tag` in it: its /// header reads, and its pixel data can't be decoded. -fn cut_image(format: image::ImageFormat, tag: &[u8], keep: usize) -> Vec { +fn cut_image(format: craft_image_codecs::Format, tag: &[u8], keep: usize) -> Vec { let mut out = vec![]; - image::RgbaImage::from_pixel(4, 2, image::Rgba([255, 0, 0, 255])).write_to(&mut std::io::Cursor::new(&mut out), format).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(4, 2, image::Rgba([255, 0, 0, 255]))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, format, &craft_image_codecs::EncodeOptions::default()).map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); let at = out.windows(tag.len()).position(|w| w == tag).expect("tag"); out.truncate(at + tag.len() + keep); out @@ -837,10 +921,10 @@ fn an_image_whose_pixels_cant_be_decoded_is_left_out_with_one_note() { let mut d = doc(200.0, 300.0); let blobs = [ ("good", ImageBlob::new("image/png", tiny_png())), - ("png", ImageBlob::new("image/png", cut_image(image::ImageFormat::Png, b"IDAT", 4))), - ("png2", ImageBlob::new("image/png", cut_image(image::ImageFormat::Png, b"IDAT", 6))), - ("gif", ImageBlob::new("image/gif", cut_image(image::ImageFormat::Gif, b"GIF89a", 7))), - ("webp", ImageBlob::new("image/webp", cut_image(image::ImageFormat::WebP, b"VP8L", 9))), + ("png", ImageBlob::new("image/png", cut_image(craft_image_codecs::Format::Png, b"IDAT", 4))), + ("png2", ImageBlob::new("image/png", cut_image(craft_image_codecs::Format::Png, b"IDAT", 6))), + ("gif", ImageBlob::new("image/gif", cut_image(craft_image_codecs::Format::Gif, b"GIF89a", 7))), + ("webp", ImageBlob::new("image/webp", cut_image(craft_image_codecs::Format::WebP, b"VP8L", 9))), ]; for (i, (key, blob)) in blobs.into_iter().enumerate() { d.images.insert(key.into(), blob); diff --git a/crates/pdf/src/tests/cmykimages.rs b/crates/pdf/src/tests/cmykimages.rs index 4719beec70..fe45d91f55 100644 --- a/crates/pdf/src/tests/cmykimages.rs +++ b/crates/pdf/src/tests/cmykimages.rs @@ -17,9 +17,9 @@ use crate::*; /// `inks` (four bytes a pixel) as a CMYK JPEG: Adobe's inverted samples, with its marker. fn cmyk_jpeg(inks: &[u8], w: u16, h: u16) -> Vec { - let mut out = Vec::new(); - jpeg_encoder::Encoder::new(&mut out, 100).encode(inks, w, h, jpeg_encoder::ColorType::Cmyk).unwrap(); - out + let img = craft_image_codecs::Image::from_u8(u32::from(w), u32::from(h), craft_image_codecs::ChannelLayout::Cmyk, inks.to_vec()).unwrap(); + let opts = craft_image_codecs::EncodeOptions { jpeg_quality: 100, embed_icc: false, embed_metadata: false, ..Default::default() }; + craft_image_codecs::encode(&img, craft_image_codecs::Format::Jpeg, &opts).unwrap() } fn flat(inks: [u8; 4], n: usize) -> Vec { @@ -267,7 +267,24 @@ fn masked_cmyk_images_keep_their_inks_and_carry_the_mask_as_an_opacity_mask() { assert!(close(&blob.cmyk().unwrap().data, want, 0), "the inks as they were"); let (mblob, mw, mh) = mask.expect("an opacity mask"); assert_eq!((mw, mh), (2, 2)); - let grey = image::load_from_memory(&mblob.bytes).unwrap().to_luma8(); + let grey = craft_image_codecs::decode(&mblob.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_luma8(); assert_eq!(grey.into_raw(), alpha, "the mask's values"); } // The mask art covers the image exactly. @@ -431,7 +448,26 @@ fn the_output_settings_convert_cmyk_images_and_compression_recompresses_them_in_ let (w, blob, _) = first(json!({"output": {"conversion": "destination", "destination": SRGB}})); assert_eq!(w.space, "DeviceRGB"); let shown = source.cmyk_to_srgb(ink.map(|v| v as f32 / 255.0), false).map(|v| (v * 255.0).round() as u8); - let px = image::load_from_memory(&blob.bytes).unwrap().to_rgb8().get_pixel(0, 0).0; + let px = craft_image_codecs::decode(&blob.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgb8() + .get_pixel(0, 0) + .0; assert!(close(&px, &shown, 3), "{px:?} vs {shown:?}"); // JPEG compression: a CMYK JPEG (Adobe's inverted samples, undone by the Decode array). let (w, blob, warnings) = first(json!({"compression": {"color": {"compression": "jpeg", "quality": "maximum"}}})); @@ -474,11 +510,10 @@ fn cmyk_profile(edit: impl FnOnce(&mut Vec)) -> Vec { /// `inks` (four bytes a pixel) as a CMYK JPEG carrying `icc` in its `ICC_PROFILE` segments. fn cmyk_jpeg_with(inks: &[u8], w: u16, h: u16, icc: &[u8]) -> Vec { - let mut out = Vec::new(); - let mut e = jpeg_encoder::Encoder::new(&mut out, 100); - e.add_icc_profile(icc).unwrap(); - e.encode(inks, w, h, jpeg_encoder::ColorType::Cmyk).unwrap(); - out + let mut img = craft_image_codecs::Image::from_u8(u32::from(w), u32::from(h), craft_image_codecs::ChannelLayout::Cmyk, inks.to_vec()).unwrap(); + img.icc = Some(icc.to_vec()); + let opts = craft_image_codecs::EncodeOptions { jpeg_quality: 100, embed_icc: true, embed_metadata: false, ..Default::default() }; + craft_image_codecs::encode(&img, craft_image_codecs::Format::Jpeg, &opts).unwrap() } /// A CMYK TIFF of `w` × `h` pixels of `ink` carrying `icc` as its tag 34675 (written as Open @@ -720,7 +755,41 @@ fn export_smasks(d: &Document) -> (Vec, Vec>>) { fn png(img: impl Into) -> Vec { let mut out = Vec::new(); - img.into().write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img.into()).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); out } @@ -968,7 +1037,24 @@ fn freeform_gradients_of_lab_points_are_written_as_their_lab_mix() { let out = export_with_report(&d, &opts(json!({}))).unwrap(); assert_eq!(written(&out.bytes)[0].space, "DeviceRGB"); let back = import(&out.bytes).unwrap(); - let px = image::load_from_memory(&all_images(&back)[0].bytes).unwrap().to_rgba8(); + let px = craft_image_codecs::decode(&all_images(&back)[0].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); let got = px.get_pixel(px.width() / 2, px.height() / 2).0; let want = Color::lab(60.0, 0.0, 0.0).to_rgba8(1.0); assert!(close(&got, &want, 6), "{got:?} vs {want:?}"); diff --git a/crates/pdf/src/tests/colorize.rs b/crates/pdf/src/tests/colorize.rs index 207c9fc595..48b21dd1ca 100644 --- a/crates/pdf/src/tests/colorize.rs +++ b/crates/pdf/src/tests/colorize.rs @@ -19,7 +19,41 @@ fn doc(mode: ColorMode, colorize: Option) -> Document { d.swatches.push(Swatch { name: "Ink".into(), paint: Paint::solid(Color::cmyk(0.0, 1.0, 1.0, 0.0)), global: true, spot: true }); let gray = image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap(); let mut png = vec![]; - gray.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (gray).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); d.images.insert("pic".into(), ImageBlob::png(png)); let im = ImageObject { key: "pic".into(), width: 2, height: 1, xf: Affine::scale(20.0), link: None, placement: Default::default(), pixels: None }; let mut n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))); @@ -110,7 +144,41 @@ fn colorized_images_are_downsampled() { let mut d = Document::new(100.0, 100.0); let gray = image::GrayImage::from_fn(600, 600, |x, y| image::Luma([((x + y) % 200) as u8])); let mut png = vec![]; - gray.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (gray).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); d.images.insert("pic".into(), ImageBlob::png(png)); // One inch wide: 600 ppi. let im = ImageObject { @@ -141,7 +209,41 @@ fn a_colorized_warped_image_is_written_once_for_all_its_pieces() { let mut d = Document::new(100.0, 100.0); let gray = image::GrayImage::from_fn(600, 600, |x, y| image::Luma([((x + y) % 200) as u8])); let mut png = vec![]; - gray.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (gray).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); d.images.insert("pic".into(), ImageBlob::png(png)); let im = ImageObject { key: "pic".into(), @@ -208,11 +310,10 @@ fn separations_print_a_color_masked_image_as_it_shows() { let spot = Paint::Solid { color: Color::cmyk(0.0, 1.0, 1.0, 0.0), swatch: Some("Ink".into()), tint: 1.0 }; let mut d = doc(ColorMode::Cmyk, Some(spot)); // The black pixel hidden. - let mut png = vec![]; - image::GrayAlphaImage::from_raw(2, 1, vec![0, 0, 255, 255]) - .unwrap() - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + let img = + craft_image_codecs::Image::from_raw(2, 1, craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, vec![0, 0, 255, 255]) + .unwrap(); + let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); d.images.insert("shown".into(), ImageBlob::png(png)); let id = d.layers[0].children().unwrap()[0].id; d.node_mut(id).unwrap().extras_mut().color_mask = Some(Box::new(vectorcraft_doc::color_mask::ColorMask { @@ -243,11 +344,10 @@ fn separations_colorize_masked_pixels_whose_own_pixels_are_a_preview() { let mut d = doc(ColorMode::Cmyk, Some(spot)); let preview = Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap()); d.images.insert("pic".into(), ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview) }); - let mut png = vec![]; - image::GrayAlphaImage::from_raw(2, 1, vec![0, 0, 255, 255]) - .unwrap() - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + let img = + craft_image_codecs::Image::from_raw(2, 1, craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, vec![0, 0, 255, 255]) + .unwrap(); + let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); d.images.insert("shown".into(), ImageBlob::png(png)); let id = d.layers[0].children().unwrap()[0].id; d.node_mut(id).unwrap().extras_mut().color_mask = Some(Box::new(vectorcraft_doc::color_mask::ColorMask { @@ -342,7 +442,23 @@ fn imported_images(d: &Document) -> Vec<(Option, Vec)> { l.walk(&mut |n| { if let NodeKind::Image(im) = &n.kind { let blob = d.images.get(&im.key).unwrap(); - let gray = image::load_from_memory(&blob.bytes).unwrap(); + let gray = craft_image_codecs::decode(&blob.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap(); assert_eq!(gray.color(), image::ColorType::L8, "a grayscale image"); out.push((n.extras().colorize.as_deref().cloned(), gray.into_luma8().into_raw())); } @@ -506,8 +622,9 @@ fn a_separation_image_drawn_twice_is_colorized_twice() { /// A one-component JPEG in a Separation space is read through its decoder. #[test] fn a_separation_jpeg_opens_colorized_by_its_ink() { - let mut jpeg = vec![]; - jpeg_encoder::Encoder::new(&mut jpeg, 100).encode(&[0, 0, 255, 255, 0, 0, 255, 255], 8, 1, jpeg_encoder::ColorType::Luma).unwrap(); + let img = craft_image_codecs::Image::from_u8(8, 1, craft_image_codecs::ChannelLayout::Gray, vec![0, 0, 255, 255, 0, 0, 255, 255]).unwrap(); + let opts = craft_image_codecs::EncodeOptions { jpeg_quality: 100, embed_icc: false, embed_metadata: false, ..Default::default() }; + let jpeg = craft_image_codecs::encode(&img, craft_image_codecs::Format::Jpeg, &opts).unwrap(); let hex: String = jpeg.iter().map(|b| format!("{b:02X}")).collect(); let d = separation_page(SPOT_RED, 8, 8, "/Filter [/ASCIIHexDecode /DCTDecode]", &hex, &[]); let images = imported_images(&d); diff --git a/crates/pdf/src/tests/compression.rs b/crates/pdf/src/tests/compression.rs index 076c3c08c9..35e12f0f16 100644 --- a/crates/pdf/src/tests/compression.rs +++ b/crates/pdf/src/tests/compression.rs @@ -6,7 +6,7 @@ use std::io::Cursor; use craft_pdf::syntax::object::{Name, Object}; -use image::{DynamicImage, ImageFormat}; +use image::DynamicImage; use serde_json::{Value, json}; use vectorcraft_doc::{Document, ImageBlob, ImageObject, Node, NodeKind}; use vectorcraft_geom::{Affine, Point}; @@ -15,7 +15,40 @@ use crate::*; fn encoded(img: DynamicImage, format: ImageFormat) -> Vec { let mut out = Vec::new(); - img.write_to(&mut Cursor::new(&mut out), format).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, format, &craft_image_codecs::EncodeOptions::default()).map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); out } @@ -57,7 +90,7 @@ fn pdf(d: &Document, compression: Value) -> (String, Vec) { #[test] fn images_above_the_threshold_are_resampled_to_the_target_resolution() { - let d = doc(encoded(colour(), ImageFormat::Png), "image/png"); + let d = doc(encoded(colour(), craft_image_codecs::Format::Png), "image/png"); for method in ["average", "subsample", "bicubic"] { let (text, warnings) = pdf(&d, json!({"color": {"downsample": method, "ppi": 150, "abovePpi": 225}})); assert!(text.contains("/Width 150") && text.contains("/Height 150"), "{method}"); @@ -68,7 +101,7 @@ fn images_above_the_threshold_are_resampled_to_the_target_resolution() { assert!(pdf(&d, c.clone()).0.contains("/Width 600"), "{c}"); } // Greyscale images take the greyscale settings. - let grey = doc(encoded(colour().grayscale(), ImageFormat::Png), "image/png"); + let grey = doc(encoded(colour().grayscale(), craft_image_codecs::Format::Png), "image/png"); let (text, _) = pdf(&grey, json!({"color": {"downsample": "bicubic", "ppi": 150}, "gray": {"downsample": "bicubic", "ppi": 100}})); assert!(text.contains("/Width 100") && text.contains("/DeviceGray"), "grey at 100 ppi"); } @@ -78,7 +111,7 @@ fn images_above_the_threshold_are_resampled_to_the_target_resolution() { #[test] fn resampled_images_keep_their_color_beside_clear_pixels() { let striped = image::RgbaImage::from_fn(600, 600, |x, _| if x % 2 == 0 { image::Rgba([200, 30, 30, 255]) } else { image::Rgba([0, 0, 0, 0]) }); - let d = doc(encoded(striped.into(), ImageFormat::Png), "image/png"); + let d = doc(encoded(striped.into(), craft_image_codecs::Format::Png), "image/png"); for method in ["average", "bicubic"] { let mut settings: PdfSettings = serde_json::from_value(json!({"compression": {"color": {"downsample": method, "ppi": 150, "abovePpi": 225, "compression": "zip"}}})) @@ -126,7 +159,7 @@ fn image_sizes(pdf: &[u8]) -> Vec<(u32, u32)> { fn a_warped_image_is_written_once_for_all_its_pieces() { let compression = json!({"color": {"downsample": "bicubic", "ppi": 150, "abovePpi": 225}}); for masked in [false, true] { - let mut d = doc(encoded(colour(), ImageFormat::Png), "image/png"); + let mut d = doc(encoded(colour(), craft_image_codecs::Format::Png), "image/png"); let id = d.layers[0].children().unwrap()[0].id; let n = d.node(id).unwrap().clone(); let NodeKind::Image(im) = &n.kind else { panic!("the image") }; @@ -156,8 +189,8 @@ fn a_warped_image_is_written_once_for_all_its_pieces() { #[test] fn jpeg_zip_and_automatic_compression() { - let png = doc(encoded(colour(), ImageFormat::Png), "image/png"); - let jpeg = doc(encoded(colour(), ImageFormat::Jpeg), "image/jpeg"); + let png = doc(encoded(colour(), craft_image_codecs::Format::Png), "image/png"); + let jpeg = doc(encoded(colour(), craft_image_codecs::Format::Jpeg), "image/jpeg"); let dct = |d: &Document, c: Value| pdf(d, c).0.contains("/DCTDecode"); assert!(dct(&png, json!({"color": {"compression": "jpeg", "quality": "low"}})), "JPEG compression"); assert!(!dct(&png, json!({"color": {"compression": "zip"}})) && pdf(&png, json!({})).0.contains("/FlateDecode"), "ZIP"); @@ -167,7 +200,7 @@ fn jpeg_zip_and_automatic_compression() { // JPEG has no transparency: an image with some stays lossless. let mut clear = colour().to_rgba8(); clear.put_pixel(0, 0, image::Rgba([0, 0, 0, 0])); - let clear = doc(encoded(clear.into(), ImageFormat::Png), "image/png"); + let clear = doc(encoded(clear.into(), craft_image_codecs::Format::Png), "image/png"); let (text, _) = pdf(&clear, json!({"color": {"compression": "jpeg"}})); assert!(!text.contains("/DCTDecode") && text.contains("/SMask")); } @@ -184,7 +217,7 @@ fn sixteen_bit_images_are_written_at_8_bits_before_pdf_1_5() { ("RGBA", DynamicImage::ImageRgba16(clear.to_rgba16()), clear), ]; for (kind, deep, pixels) in images { - let d = doc(encoded(deep, ImageFormat::Png), "image/png"); + let d = doc(encoded(deep, craft_image_codecs::Format::Png), "image/png"); // PDF/X-1a and PDF/X-3 files are PDF 1.3. A PDF 1.3 file has no soft masks: the app // flattens an image with transparency before it is written. let mut cases = vec![(json!({"compatibility": "1.4"}), 8), (json!({"compatibility": "1.5"}), 16), (json!({"compatibility": "1.7"}), 16)]; @@ -210,14 +243,31 @@ fn sixteen_bit_images_are_written_at_8_bits_before_pdf_1_5() { // The image reads back with the 8-bit pixels (within 1 for the PDF/X-3 file's RGB // image, which is tagged with the sRGB profile). let back = import(&r.bytes).unwrap(); - let got = image::load_from_memory(&back.images.values().next().unwrap().bytes).unwrap().to_rgba8(); + let got = craft_image_codecs::decode(&back.images.values().next().unwrap().bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); let close = got.dimensions() == (600, 600) && got.as_raw().iter().zip(pixels.to_rgba8().as_raw()).all(|(a, b)| a.abs_diff(*b) <= 1); assert!(back.images.len() == 1 && close, "{kind}, {case}: the pixels"); } } } // A 16-bit PNG whose pixel data can't be decoded is left out with the note. - let mut cut = encoded(DynamicImage::ImageRgb16(colour().to_rgb16()), ImageFormat::Png); + let mut cut = encoded(DynamicImage::ImageRgb16(colour().to_rgb16()), craft_image_codecs::Format::Png); let at = cut.windows(4).position(|w| w == b"IDAT").unwrap(); cut.truncate(at + 10); let settings = serde_json::from_value(json!({"compatibility": "1.4"})).unwrap(); @@ -227,13 +277,13 @@ fn sixteen_bit_images_are_written_at_8_bits_before_pdf_1_5() { #[test] fn codecs_the_writer_lacks_are_zip_with_a_warning() { - let png = doc(encoded(colour(), ImageFormat::Png), "image/png"); + let png = doc(encoded(colour(), craft_image_codecs::Format::Png), "image/png"); let (text, warnings) = pdf(&png, json!({"color": {"compression": "jpeg2000"}})); assert!(!text.contains("/JPXDecode") && text.contains("/FlateDecode")); assert!(warnings.len() == 1 && warnings[0].contains("JPEG 2000"), "{warnings:?}"); // Black-and-white images are monochrome: their settings apply, CCITT becomes ZIP. let bw = image::GrayImage::from_fn(600, 600, |x, y| image::Luma([if (x / 7 + y / 5) % 2 == 0 { 0 } else { 255 }])); - let bw = doc(encoded(bw.into(), ImageFormat::Png), "image/png"); + let bw = doc(encoded(bw.into(), craft_image_codecs::Format::Png), "image/png"); let (text, warnings) = pdf(&bw, json!({"mono": {"downsample": "bicubic", "ppi": 300, "abovePpi": 450, "compression": "ccittG4"}})); assert!(text.contains("/Width 300") && !text.contains("/CCITTFaxDecode")); assert!(warnings.len() == 1 && warnings[0].contains("CCITT"), "{warnings:?}"); diff --git a/crates/pdf/src/tests/import_fidelity.rs b/crates/pdf/src/tests/import_fidelity.rs index abb15552da..251cc925bf 100644 --- a/crates/pdf/src/tests/import_fidelity.rs +++ b/crates/pdf/src/tests/import_fidelity.rs @@ -112,7 +112,24 @@ fn mask_image_pixels(s: &str) -> [[u8; 4]; 2] { } }); let [key] = keys.as_slice() else { panic!("one image in the mask art: {keys:?}") }; - let px = image::load_from_memory(&d.images[key].bytes).unwrap().to_rgba8(); + let px = craft_image_codecs::decode(&d.images[key].bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); [px.get_pixel(0, 0).0, px.get_pixel(1, 0).0] } diff --git a/crates/pdf/src/tests/output.rs b/crates/pdf/src/tests/output.rs index e0f00dc0e7..eccd946480 100644 --- a/crates/pdf/src/tests/output.rs +++ b/crates/pdf/src/tests/output.rs @@ -429,11 +429,9 @@ fn tagged_cmyk_documents_blend_in_the_cmyk_profile_space() { /// A 4 × 4 PNG of one colour. fn png(rgb: [u8; 3]) -> Vec { - let mut out = Vec::new(); - image::DynamicImage::from(image::RgbImage::from_pixel(4, 4, image::Rgb(rgb))) - .write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png) + let img = craft_image_codecs::Image::from_raw(4, 4, craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, rgb.repeat(16)) .unwrap(); - out + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap() } fn image_doc(bytes: Vec) -> Document { @@ -451,7 +449,26 @@ fn image_doc(bytes: Vec) -> Document { fn first_pixel(bytes: &[u8]) -> [u8; 3] { let back = import(bytes).unwrap(); let blob = back.images.values().next().unwrap(); - image::load_from_memory(&blob.bytes).unwrap().to_rgb8().get_pixel(0, 0).0 + craft_image_codecs::decode(&blob.bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgb8() + .get_pixel(0, 0) + .0 } #[test] diff --git a/crates/pdf/src/tests/pdfx.rs b/crates/pdf/src/tests/pdfx.rs index ec22eb0186..83409bc38a 100644 --- a/crates/pdf/src/tests/pdfx.rs +++ b/crates/pdf/src/tests/pdfx.rs @@ -113,7 +113,41 @@ fn pdfx_1a_files_have_no_rgb() { let png = { let img = image::RgbaImage::from_pixel(4, 4, image::Rgba([10, 200, 30, 255])); let mut out = std::io::Cursor::new(vec![]); - img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); out.into_inner() }; d.images.insert("img".into(), ImageBlob::new("image/png", png)); diff --git a/crates/pdf/src/tests/webview.rs b/crates/pdf/src/tests/webview.rs index 6fc50d0d54..30e3d4331e 100644 --- a/crates/pdf/src/tests/webview.rs +++ b/crates/pdf/src/tests/webview.rs @@ -35,9 +35,42 @@ fn doc(n: usize, image: bool, on_first: bool) -> Document { }); } let mut png = vec![]; - DynamicImage::from(image::RgbImage::from_fn(8, 8, |x, y| image::Rgb([(x * 30) as u8, (y * 30) as u8, 90]))) - .write_to(&mut Cursor::new(&mut png), ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = + (DynamicImage::from(image::RgbImage::from_fn(8, 8, |x, y| image::Rgb([(x * 30) as u8, (y * 30) as u8, 90])))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); d.images.insert("img".into(), ImageBlob::new("image/png", png)); let layer = d.default_layer().unwrap(); for i in 0..n { diff --git a/crates/plugins/Cargo.toml b/crates/plugins/Cargo.toml index ef21a57ef4..28b972d679 100644 --- a/crates/plugins/Cargo.toml +++ b/crates/plugins/Cargo.toml @@ -16,7 +16,7 @@ log = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } # The pixels of a small image a filter asks to read, as RGBA in base64. -image = { workspace = true } +craft-image-codecs = { workspace = true } craft-vectorcraft-format = { workspace = true } # The SHA-256 of a module, which the install prompt shows and a grant records. sha2 = { version = "0.10", default-features = false } diff --git a/crates/plugins/src/objects.rs b/crates/plugins/src/objects.rs index 192ed24a96..fa14ed1bee 100644 --- a/crates/plugins/src/objects.rs +++ b/crates/plugins/src/objects.rs @@ -459,9 +459,8 @@ fn color_mode(b: &ImageBlob) -> &'static str { if b.gray_source().is_some() { return "gray"; } - let readable = - image::ImageReader::new(std::io::Cursor::new(b.bytes.as_slice())).with_guessed_format().ok().and_then(|r| r.into_dimensions().ok()); - if readable.is_some() { "rgb" } else { "unknown" } + let readable = craft_image_codecs::probe_size(&b.bytes).is_ok() || b.header_size().is_some(); + if readable { "rgb" } else { "unknown" } } #[cfg(test)] @@ -481,8 +480,7 @@ fn rgba_pixels(b: &ImageBlob, w: u32, h: u32, max: usize, charged: &mut usize) - return None; } let cmyk = b.is_cmyk(); - let reader = || image::ImageReader::new(std::io::Cursor::new(b.bytes.as_slice())).with_guessed_format().ok(); - let size = if cmyk { b.header_size()? } else { reader()?.into_dimensions().ok()? }; + let size = if cmyk { b.header_size()? } else { craft_image_codecs::probe_size(&b.bytes).ok().or_else(|| b.header_size())? }; if size != (w, h) { return None; } @@ -492,13 +490,11 @@ fn rgba_pixels(b: &ImageBlob, w: u32, h: u32, max: usize, charged: &mut usize) - if cmyk { return cmyk_rgba(b, w, h); } - let mut r = reader()?; - let mut limits = image::Limits::default(); + let mut opts = craft_image_codecs::DecodeOptions::default(); // The decoder's own buffers besides the RGBA it gives. - limits.max_alloc = Some(64 << 20); - r.limits(limits); - let img = r.decode().ok()?.into_rgba8(); - (img.dimensions() == (w, h)).then(|| img.into_raw()) + opts.limits.max_alloc = 64 << 20; + let img = craft_image_codecs::decode_with(&b.bytes, &opts).ok()?; + (img.dimensions() == (w, h)).then(|| img.to_rgba8()) } /// The inks → XYZ table of [`cmyk_rgba`] and the color settings it was built with. diff --git a/crates/plugins/src/objects/tests.rs b/crates/plugins/src/objects/tests.rs index 5fb48cf396..266309b964 100644 --- a/crates/plugins/src/objects/tests.rs +++ b/crates/plugins/src/objects/tests.rs @@ -450,10 +450,14 @@ fn bad_stroke_styles_and_effect_records_are_refused() { /// A `w` × `h` PNG whose pixels vary with their column, half transparent. fn png(w: u32, h: u32) -> Vec { - let img = image::RgbaImage::from_fn(w, h, |x, y| image::Rgba([(x * 100) as u8, (y * 7) as u8, 30, 128])); - let mut out = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); - out + let mut data = Vec::with_capacity((w * h * 4) as usize); + for y in 0..h { + for x in 0..w { + data.extend_from_slice(&[(x * 100) as u8, (y * 7) as u8, 30, 128]); + } + } + let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, data).unwrap(); + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap() } /// An image object `w` × `h` pixels showing blob `key`, linked to `link`. @@ -590,8 +594,11 @@ fn declared_embedded_and_linked_images_have_distinct_metadata_and_pixel_omission let id = d.insert(Some(layer), usize::MAX, n).unwrap(); assert_eq!(encode_read_only(&d, d.node(id).unwrap()).unwrap()["pixelsOmitted"], json!(true), "too large to count"); // Gray pixels, and data that isn't an image. - let mut gray = vec![]; - image::GrayImage::from_pixel(2, 2, image::Luma([90])).write_to(&mut std::io::Cursor::new(&mut gray), image::ImageFormat::Png).unwrap(); + let gray = craft_image_codecs::encode( + &craft_image_codecs::Image::from_raw(2, 2, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, vec![90; 4]).unwrap(), + craft_image_codecs::Format::Png, + ) + .unwrap(); for (blob, mode) in [(ImageBlob::png(gray), "gray"), (ImageBlob::png(b"not an image".to_vec()), "unknown")] { d.images.insert("x".into(), blob); let n = image_node(&mut d, "x", (2, 2), None); diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index ecdaa60273..d706f69242 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -19,12 +19,10 @@ vello_cpu = { workspace = true } # Filter types (Gaussian blur, drop shadow) are not re-exported by vello_cpu 0.2. vello_common = { version = "0.2", default-features = false } image = { workspace = true } +craft-gif = { workspace = true } craft-image-codecs = { workspace = true } +craft-stream-codecs = { workspace = true } flate2 = { workspace = true } -jpeg-encoder = { workspace = true } -gif = { workspace = true } -# TIFF LZW compression (MIT OR Apache-2.0; already used by the image crate's TIFF reader). -weezl = "0.2" log = { workspace = true } # Combining marks inside a lam-alef cluster (MIT OR Apache-2.0; already used by vectorcraft-text). unicode-general-category = "1" @@ -45,7 +43,7 @@ vectorcraft-text = { workspace = true, features = ["test-fonts"] } vectorcraft-plugins = { workspace = true } wat = { workspace = true } # Decoders the export tests read their files back with. -image = { workspace = true, features = ["tga"] } +image = { workspace = true } craft-tiff = { workspace = true } craft-psd = { workspace = true } proptest = { workspace = true } diff --git a/crates/render/src/blobs.rs b/crates/render/src/blobs.rs index ab5d831a0b..4378494d32 100644 --- a/crates/render/src/blobs.rs +++ b/crates/render/src/blobs.rs @@ -42,13 +42,7 @@ pub(crate) fn blob_pixmap(blob: &vectorcraft_doc::ImageBlob, touch: bool) -> Opt // Decoded outside the lock: other renderers carry on meanwhile. The inks and the pixels // shown from them are admitted together, as other images are, before either is made: // without room the image is read as other images are (which reduces it). - let room = || { - image::ImageReader::new(std::io::Cursor::new(blob.bytes.as_slice())) - .with_guessed_format() - .ok() - .and_then(|r| r.into_dimensions().ok()) - .is_some_and(|(w, h)| paint::within_allowance(w, h.saturating_mul(2))) - }; + let room = || blob.header_size().is_some_and(|(w, h)| paint::within_allowance(w, h.saturating_mul(2))); let pm = match lut.filter(|_| room()).and_then(|lut| ink::cmyk_pixmap(blob, &lut)) { Some(pm) => pm, None => match paint::decode_pixmap_or_why(&blob.bytes) { diff --git a/crates/render/src/encode.rs b/crates/render/src/encode.rs index 635f906839..e58e499137 100644 --- a/crates/render/src/encode.rs +++ b/crates/render/src/encode.rs @@ -185,11 +185,16 @@ pub fn on_white(p: &[u8; 4]) -> [u8; 3] { /// Lossless WebP. pub(crate) fn webp(img: &Rendered) -> Result, String> { - let mut buf = Vec::new(); - let enc = image::codecs::webp::WebPEncoder::new_lossless(&mut buf); - image::ImageEncoder::write_image(enc, &img.to_straight(), img.width, img.height, image::ExtendedColorType::Rgba8) - .map_err(|e| format!("WebP encoding failed: {e}"))?; - Ok(buf) + let src = craft_image_codecs::Image::from_raw( + img.width, + img.height, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + img.to_straight(), + ) + .map_err(|e| format!("WebP encoding failed: {e}"))?; + let opts = craft_image_codecs::EncodeOptions { webp_lossless: true, ..craft_image_codecs::EncodeOptions::default() }; + craft_image_codecs::encode(&src, craft_image_codecs::Format::WebP, &opts).map_err(|e| format!("WebP encoding failed: {e}")) } /// Bounds of the art an export draws: visible objects off template layers (guides left out), diff --git a/crates/render/src/encode/gif.rs b/crates/render/src/encode/gif.rs index 3d9760895c..4ca0e92a45 100644 --- a/crates/render/src/encode/gif.rs +++ b/crates/render/src/encode/gif.rs @@ -1,33 +1,21 @@ //! GIF export: a palette image ([`super::quantize`]) as a one-frame GIF89a with its transparent //! entry, optionally interlaced (rows in four passes, so the image builds up while it loads). -use std::borrow::Cow; - use super::quantize::Indexed; /// Encode `img` as a GIF file. pub fn encode(img: &Indexed, interlaced: bool) -> Result, String> { - let fail = |e: gif::EncodingError| format!("GIF encoding failed: {e}"); - let (Ok(w), Ok(h)) = (u16::try_from(img.width), u16::try_from(img.height)) else { + if img.width > u32::from(u16::MAX) || img.height > u32::from(u16::MAX) { return Err(format!("{} × {} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution", img.width, img.height)); - }; - if w == 0 || h == 0 || img.indices.len() != w as usize * h as usize || img.palette.is_empty() || img.palette.len() > 256 { + } + if img.width == 0 + || img.height == 0 + || img.indices.len() != img.width as usize * img.height as usize + || img.palette.is_empty() + || img.palette.len() > 256 + { return Err("GIF encoding failed: the palette image is malformed".into()); } - let buffer = if interlaced { Cow::Owned(interlace(&img.indices, w as usize)) } else { Cow::Borrowed(img.indices.as_slice()) }; - let mut enc = gif::Encoder::new(Vec::new(), w, h, &img.palette.concat()).map_err(fail)?; - let frame = gif::Frame { width: w, height: h, buffer, transparent: img.transparent, interlaced, ..gif::Frame::default() }; - enc.write_frame(&frame).map_err(fail)?; - enc.into_inner().map_err(fail) -} - -/// The rows of a `width`-wide image in GIF's interlaced order: every 8th row from 0, every 8th -/// from 4, every 4th from 2, then every 2nd from 1. -fn interlace(px: &[u8], width: usize) -> Vec { - let rows: Vec<&[u8]> = px.chunks(width.max(1)).collect(); - [(0, 8), (4, 8), (2, 4), (1, 2)] - .into_iter() - .flat_map(|(start, step)| rows.iter().skip(start).step_by(step)) - .flat_map(|r| r.iter().copied()) - .collect() + craft_gif::write::encode_indexed(img.width, img.height, &img.palette, &img.indices, img.transparent, interlaced) + .map_err(|e| format!("GIF encoding failed: {e}")) } diff --git a/crates/render/src/encode/jpeg.rs b/crates/render/src/encode/jpeg.rs index 596399c3e7..6726b6812b 100644 --- a/crates/render/src/encode/jpeg.rs +++ b/crates/render/src/encode/jpeg.rs @@ -5,7 +5,7 @@ use std::collections::HashMap; -use jpeg_encoder::{ColorType, Density, Encoder}; +use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, JpegFormat}; use vectorcraft_color::cms::{self, lab}; use crate::Rendered; @@ -124,97 +124,41 @@ impl Default for JpegOptions { /// Encode `px` (`o.color_model`'s channels per pixel: RGB, CMYK ink amounts with 0 = no ink, or /// grey) at `quality` 0–100, with the resolution `ppi` (if any) in the JFIF header. pub fn encode(px: &[u8], width: u32, height: u32, quality: u8, ppi: Option, o: &JpegOptions) -> Result, String> { - let fail = |e: jpeg_encoder::EncodingError| format!("JPEG encoding failed: {e}"); - let (Ok(w), Ok(h)) = (u16::try_from(width), u16::try_from(height)) else { + if u16::try_from(width).is_err() || u16::try_from(height).is_err() { return Err(format!("{width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution")); - }; + } if px.len() as u64 != u64::from(width) * u64::from(height) * o.color_model.channels() as u64 { return Err("JPEG encoding failed: pixel buffer doesn't match the image size".into()); } - let mut buf = Vec::new(); - let mut enc = Encoder::new(&mut buf, quality.clamp(1, 100)); - if let Some(ppi) = ppi { - let d = ppi.round().clamp(1.0, u16::MAX as f64) as u16; - enc.set_density(Density::Inch { x: d, y: d }); - } - match o.method { - Method::Baseline => {} - Method::Optimized => enc.set_optimized_huffman_tables(true), - Method::Progressive => { - enc.set_optimized_huffman_tables(true); - enc.set_progressive_scans(o.scans.clamp(*SCANS.start(), *SCANS.end())); - } + let layout = match o.color_model { + ColorModel::Rgb => ChannelLayout::Rgb, + ColorModel::Cmyk => ChannelLayout::Cmyk, + ColorModel::Gray => ChannelLayout::Gray, + }; + let mut img = Image::from_u8(width, height, layout, px.to_vec()).map_err(|e| format!("JPEG encoding failed: {e}"))?; + if let Some(ppi) = ppi.filter(|p| p.is_finite() && *p >= 1.0) { + let d = ppi.round().clamp(1.0, f64::from(u16::MAX)) as f32; + img.meta.dpi = Some((d, d)); } if o.embed_icc { let icc = cms::icc_bytes(&o.color_model.profile()).map_err(|e| format!("JPEG colour profile: {e}"))?; - enc.add_icc_profile(&icc).map_err(fail)?; + img.icc = Some(icc); } - let ty = match o.color_model { - ColorModel::Rgb => ColorType::Rgb, - ColorModel::Cmyk => ColorType::Cmyk, - ColorModel::Gray => ColorType::Luma, + let (jpeg_format, jpeg_progressive_scans) = match o.method { + Method::Baseline => (JpegFormat::Baseline, None), + Method::Optimized => (JpegFormat::Optimized, None), + Method::Progressive => (JpegFormat::Progressive, Some(o.scans.clamp(*SCANS.start(), *SCANS.end()))), }; - enc.encode(px, w, h, ty).map_err(fail)?; - // JFIF describes one- and three-component images (greyscale and YCbCr), so its APP0 segment - // must not head a four-component CMYK frame: the file then says two different things about - // its colours, and a strict reader rejects it rather than guessing. Adobe's own CMYK JPEGs - // carry the APP14 marker the encoder already writes, and no JFIF (#3084). - if o.color_model == ColorModel::Cmyk { - unlabel_jfif(&mut buf, ppi); - } - Ok(buf) -} - -/// Replace the leading APP0/JFIF segment, which the encoder always writes, with an EXIF segment -/// carrying the same resolution (TIFF `XResolution`, `YResolution` and `ResolutionUnit`, which is -/// where a reader looks when there is no JFIF). Without a resolution the segment is simply -/// dropped. -fn unlabel_jfif(buf: &mut Vec, ppi: Option) { - // SOI, then APP0 with its two length bytes and the tag it is identified by. - let Some(head) = buf.get(..13) else { return }; - if head[..4] != [0xFF, 0xD8, 0xFF, 0xE0] || &head[6..11] != b"JFIF\0" { - return; - } - let len = usize::from(u16::from_be_bytes([head[4], head[5]])); - if 4 + len > buf.len() { - return; - } - let exif = ppi.filter(|p| p.is_finite() && *p >= 1.0).map(|p| exif_resolution(p.round() as u32)).unwrap_or_default(); - buf.splice(2..4 + len, exif); -} - -/// An APP1 EXIF segment holding `dpi` as IFD0's resolution: big-endian TIFF, three entries, each -/// rational pointing past the directory. -fn exif_resolution(dpi: u32) -> Vec { - let mut tiff = Vec::new(); - tiff.extend_from_slice(b"MM\0*"); // big-endian, TIFF magic - tiff.extend_from_slice(&8u32.to_be_bytes()); // IFD0 right after the header - tiff.extend_from_slice(&3u16.to_be_bytes()); // three entries - // Entry: tag, type (5 = rational, 3 = short), count, then the value or its offset. - let entry = |tag: u16, ty: u16, value: [u8; 4]| { - let mut e = Vec::with_capacity(12); - e.extend_from_slice(&tag.to_be_bytes()); - e.extend_from_slice(&ty.to_be_bytes()); - e.extend_from_slice(&1u32.to_be_bytes()); - e.extend_from_slice(&value); - e + let opts = EncodeOptions { + jpeg_quality: quality.clamp(1, 100), + jpeg_chroma_subsampling: false, + jpeg_format, + jpeg_progressive_scans, + embed_icc: o.embed_icc, + embed_metadata: true, + ..Default::default() }; - // The two rationals sit after the directory: header 8 + count 2 + 3 entries + next-IFD 4. - let after = 8 + 2 + 3 * 12 + 4; - tiff.extend(entry(282, 5, (after as u32).to_be_bytes())); // XResolution - tiff.extend(entry(283, 5, (after as u32 + 8).to_be_bytes())); // YResolution - tiff.extend(entry(296, 3, [0, 2, 0, 0])); // ResolutionUnit: inches - tiff.extend_from_slice(&0u32.to_be_bytes()); // no next IFD - for _ in 0..2 { - tiff.extend_from_slice(&dpi.to_be_bytes()); - tiff.extend_from_slice(&1u32.to_be_bytes()); - } - let mut seg = vec![0xFF, 0xE1]; - let body_len = 6 + tiff.len() + 2; - seg.extend_from_slice(&u16::try_from(body_len).unwrap_or(u16::MAX).to_be_bytes()); - seg.extend_from_slice(b"Exif\0\0"); - seg.extend_from_slice(&tiff); - seg + craft_image_codecs::encode(&img, Format::Jpeg, &opts).map_err(|e| format!("JPEG encoding failed: {e}")) } /// `img` flattened on white as RGB, or as grey with each colour's lightness. diff --git a/crates/render/src/encode/tests.rs b/crates/render/src/encode/tests.rs index 0a8227b75f..92c257d2dd 100644 --- a/crates/render/src/encode/tests.rs +++ b/crates/render/src/encode/tests.rs @@ -32,7 +32,25 @@ fn noise(w: u32, h: u32, opaque: bool) -> Vec { } fn decode(png: &[u8]) -> Vec { - image::load_from_memory_with_format(png, image::ImageFormat::Png).expect("decodes").to_rgba8().into_raw() + craft_image_codecs::decode_as(craft_image_codecs::Format::Png, png) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .expect("decodes") + .to_rgba8() + .into_raw() } #[test] @@ -73,7 +91,27 @@ fn png_refuses_a_buffer_of_the_wrong_size() { #[test] fn gray_and_bilevel_images_store_gray() { let header = |file: &[u8]| (file[24], file[25]); - let gray = |file: &[u8]| image::load_from_memory(file).unwrap().to_luma_alpha8().into_raw(); + let gray = |file: &[u8]| { + craft_image_codecs::decode(file) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_luma_alpha8() + .into_raw() + }; // 3 × 2, premultiplied: black, red, light grey; white, mid grey, almost black. let mut img = Rendered { width: 3, @@ -116,7 +154,24 @@ fn circle_doc() -> Document { fn export(d: &Document, format: RasterFormat, o: &RasterExportOptions) -> image::RgbaImage { let bytes = Renderer::new().export_region(d, d.artboards[0].rect, format, o).unwrap(); - image::load_from_memory(&bytes).unwrap().to_rgba8() + craft_image_codecs::decode(&bytes) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() } #[test] @@ -175,7 +230,24 @@ fn translucent_edges_over_opaque_art_stay_opaque() { (&d, RasterExportOptions { ppi: 72.0 * 0.3515625, ..Default::default() }), ] { let png = Renderer::new().export_region(doc, doc.artboards[0].rect, RasterFormat::Png, &o).unwrap(); - let img = image::load_from_memory(&png).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&png) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); let below: Vec<_> = img.pixels().filter(|p| p[3] < 255).collect(); assert!(below.is_empty(), "ppi {}: {} pixels below alpha 255, e.g. {:?}", o.ppi, below.len(), below.first()); assert_eq!(png[25], 2, "IHDR colour type: RGB"); diff --git a/crates/render/src/encode/tests_bmp.rs b/crates/render/src/encode/tests_bmp.rs index 659c00d147..f458c1999b 100644 --- a/crates/render/src/encode/tests_bmp.rs +++ b/crates/render/src/encode/tests_bmp.rs @@ -23,8 +23,25 @@ pub(super) fn art(w: u32, h: u32) -> Vec { px } -pub(super) fn decode(file: &[u8], format: image::ImageFormat) -> image::RgbaImage { - image::load_from_memory_with_format(file, format).expect("decodes").to_rgba8() +pub(super) fn decode(file: &[u8], format: craft_image_codecs::Format) -> image::RgbaImage { + craft_image_codecs::decode_as(format, file) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .expect("decodes") + .to_rgba8() } fn bmp(px: &[u8], w: u32, h: u32, o: &BmpOptions) -> Vec { @@ -41,7 +58,7 @@ fn every_depth_writes_its_bit_count_and_decodes() { assert_eq!(u32_at(&file, 2) as usize, file.len(), "file size"); assert_eq!(u16_at(&file, 28), u16::from(depth), "bit count"); assert_eq!(u32_at(&file, 38), pixels_per_metre(150.0), "resolution"); - let img = decode(&file, image::ImageFormat::Bmp); + let img = decode(&file, craft_image_codecs::Format::Bmp); assert_eq!(img.dimensions(), (w, h)); let got = img.get_pixel(5, 3).0; let want = on_white(px[(3 * w as usize + 5) * 4..][..4].try_into().unwrap()); @@ -71,13 +88,13 @@ fn rle8_and_rle4_decode_like_uncompressed() { assert_eq!(u32_at(&rle, 30), if depth == 8 { 1 } else { 2 }, "BI_RLE8 / BI_RLE4"); assert_eq!(u32_at(&rle, 34) as usize, rle.len() - u32_at(&rle, 10) as usize, "the compressed size"); assert!(rle.len() < plain.len(), "{} vs {}", rle.len(), plain.len()); - assert_eq!(decode(&rle, image::ImageFormat::Bmp), decode(&plain, image::ImageFormat::Bmp), "depth {depth}"); + assert_eq!(decode(&rle, craft_image_codecs::Format::Bmp), decode(&plain, craft_image_codecs::Format::Bmp), "depth {depth}"); } // Rows of many different pixels go in absolute mode. let noisy: Vec = (0..40u32 * 4).flat_map(|i| [(i * 37 % 256) as u8, (i * 91 % 256) as u8, (i * 13 % 256) as u8, 255]).collect(); let plain = bmp(&noisy, 40, 4, &BmpOptions { depth: 8, ..Default::default() }); let rle = bmp(&noisy, 40, 4, &BmpOptions { depth: 8, rle: true, ..Default::default() }); - assert_eq!(decode(&rle, image::ImageFormat::Bmp), decode(&plain, image::ImageFormat::Bmp)); + assert_eq!(decode(&rle, craft_image_codecs::Format::Bmp), decode(&plain, craft_image_codecs::Format::Bmp)); } #[test] @@ -91,7 +108,7 @@ fn flipped_rows_have_a_negative_height() { let offset = u32_at(&down, 10) as usize; // Top-down: the first row stored is the image's first (its transparent pixel, on white). assert_eq!(&down[offset..offset + 3], &[255, 255, 255]); - assert_eq!(decode(&up, image::ImageFormat::Bmp), decode(&down, image::ImageFormat::Bmp)); + assert_eq!(decode(&up, craft_image_codecs::Format::Bmp), decode(&down, craft_image_codecs::Format::Bmp)); } #[test] @@ -106,7 +123,7 @@ fn os2_bitmaps_have_a_core_header() { let entries = if depth <= 8 { 1 << depth } else { 0 }; assert_eq!(u32_at(&file, 10), 14 + 12 + entries * 3); let windows = bmp(&px, w, h, &BmpOptions { depth, ..Default::default() }); - assert_eq!(decode(&file, image::ImageFormat::Bmp), decode(&windows, image::ImageFormat::Bmp), "depth {depth}"); + assert_eq!(decode(&file, craft_image_codecs::Format::Bmp), decode(&windows, craft_image_codecs::Format::Bmp), "depth {depth}"); } } @@ -115,7 +132,7 @@ fn greys_and_impossible_combinations() { let (w, h) = (8, 2); let px = art(w, h); for depth in [8, 24] { - let img = decode(&bmp(&px, w, h, &BmpOptions { depth, gray: true, ..Default::default() }), image::ImageFormat::Bmp); + let img = decode(&bmp(&px, w, h, &BmpOptions { depth, gray: true, ..Default::default() }), craft_image_codecs::Format::Bmp); assert!(img.pixels().all(|p| p[0] == p[1] && p[1] == p[2]), "depth {depth}: greys"); } let bad = [ diff --git a/crates/render/src/encode/tests_jpeg.rs b/crates/render/src/encode/tests_jpeg.rs index 2bba70330e..413781de13 100644 --- a/crates/render/src/encode/tests_jpeg.rs +++ b/crates/render/src/encode/tests_jpeg.rs @@ -108,7 +108,23 @@ fn methods_write_baseline_or_progressive_frames() { assert_eq!(frame(&p3).0, 0xC2, "SOF2"); assert!(sos(&p3) > 1 && sos(&p5) > sos(&p3), "more scans: {} {}", sos(&p3), sos(&p5)); for f in [&base, &p3, &p5] { - let back = image::load_from_memory(f).unwrap(); + let back = craft_image_codecs::decode(f) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap(); assert_eq!((back.width(), back.height()), (40, 30)); } } @@ -184,7 +200,24 @@ fn cmyk_exports_keep_the_inks_of_cmyk_colours() { assert!(red[1] > 200 && red[2] > 200 && red[0] < 40, "RGB red separates to magenta and yellow: {red:?}"); let file = Renderer::new().export_region(&d, d.artboards[0].rect, RasterFormat::Jpeg, &o).unwrap(); assert_eq!(frame(&file).1, 4, "4 components"); - let back = image::load_from_memory(&file).unwrap().to_rgb8(); + let back = craft_image_codecs::decode(&file) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgb8(); assert!(back.get_pixel(3, 5).0.iter().all(|v| *v < 60), "black reads back dark: {:?}", back.get_pixel(3, 5)); let r = back.get_pixel(15, 5).0; assert!(r[0] > 180 && r[1] < 90, "red reads back red: {r:?}"); @@ -196,7 +229,24 @@ fn gray_exports_keep_the_lightness() { let o = RasterExportOptions { jpeg: JpegOptions { color_model: ColorModel::Gray, ..Default::default() }, ..Default::default() }; let file = Renderer::new().export_region(&d, d.artboards[0].rect, RasterFormat::Jpeg, &o).unwrap(); assert_eq!(frame(&file).1, 1); - let back = image::load_from_memory(&file).unwrap().to_luma8(); + let back = craft_image_codecs::decode(&file) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_luma8(); let red = back.get_pixel(15, 5)[0]; // sRGB red's relative luminance 0.2126, encoded: about 127. assert!((115..=140).contains(&red), "{red}"); diff --git a/crates/render/src/encode/tests_palette.rs b/crates/render/src/encode/tests_palette.rs index f06217f397..836b5fcf09 100644 --- a/crates/render/src/encode/tests_palette.rs +++ b/crates/render/src/encode/tests_palette.rs @@ -141,7 +141,24 @@ fn transparent_pixels_get_their_own_entry() { let file = encode_indexed(&ix, &PngOptions::default()).unwrap(); assert_eq!(chunk(&file, b"tRNS").unwrap(), [0]); - let back = image::load_from_memory(&file).unwrap().to_rgba8(); + let back = craft_image_codecs::decode(&file) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!(back.get_pixel(0, 0).0, [255, 0, 0, 255]); assert_eq!(back.get_pixel(1, 0)[3], 0); } @@ -154,7 +171,24 @@ fn png8_decodes_at_every_bit_depth_and_interlaced() { for interlaced in [false, true] { let file = encode_indexed(&ix, &PngOptions { ppi: Some(144.0), interlaced }).unwrap(); assert_eq!((file[24], file[25], file[28]), (depth, 3, u8::from(interlaced))); - let back = image::load_from_memory(&file).unwrap().to_rgb8(); + let back = craft_image_codecs::decode(&file) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgb8(); let want: Vec = colours(&ix).into_iter().flatten().collect(); assert_eq!(back.into_raw(), want, "{colors} colours, interlaced {interlaced}"); assert!(chunk(&file, b"pHYs").is_some()); @@ -169,7 +203,24 @@ fn gif_decodes() { for interlaced in [false, true] { let file = gif::encode(&ix, interlaced).unwrap(); assert_eq!(&file[..6], b"GIF89a"); - let back = image::load_from_memory_with_format(&file, image::ImageFormat::Gif).unwrap().to_rgba8(); + let back = craft_image_codecs::decode_as(craft_image_codecs::Format::Gif, &file) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!(back.dimensions(), (21, 17)); for (i, p) in back.pixels().enumerate() { match ix.indices[i] { diff --git a/crates/render/src/encode/tests_psd.rs b/crates/render/src/encode/tests_psd.rs index 7655fa16e7..9a3b227ca0 100644 --- a/crates/render/src/encode/tests_psd.rs +++ b/crates/render/src/encode/tests_psd.rs @@ -232,8 +232,9 @@ fn maximum_editability_writes_groups_and_an_object_per_layer() { assert_eq!((p.records[8].blend, p.records[8].opacity), (*b"pass", 255)); assert_eq!(p.records[6].rect, [0, 0, 6, 6]); let psd = craft_psd::PsdFile::from_bytes(&file).unwrap(); - let content_layers = psd.layers().iter().filter(|l| matches!(l.section_type(), craft_psd::layer::SectionType::Other)).count(); - let groups = psd.layers().iter().filter(|l| matches!(l.section_type(), craft_psd::layer::SectionType::OpenFolder | craft_psd::layer::SectionType::ClosedFolder)).count(); + let content_layers = psd.layers().iter().filter(|l| matches!(l.section_type(), craft_psd::SectionType::Other)).count(); + let groups = + psd.layers().iter().filter(|l| matches!(l.section_type(), craft_psd::SectionType::OpenFolder | craft_psd::SectionType::ClosedFolder)).count(); assert_eq!((content_layers, groups), (3, 3)); assert_eq!(merged(&file), merged(&export(&doc, &opts(PsdOptions::default()))), "the same merged image"); diff --git a/crates/render/src/encode/tests_tga.rs b/crates/render/src/encode/tests_tga.rs index 3f720443aa..2851a25873 100644 --- a/crates/render/src/encode/tests_tga.rs +++ b/crates/render/src/encode/tests_tga.rs @@ -14,7 +14,7 @@ fn targa_depths_alpha_and_footer() { assert_eq!((u16_at(&file, 12), u16_at(&file, 14)), (7, 3)); assert_eq!(file.len(), 18 + (w * h) as usize * usize::from(depth / 8) + 26); assert!(file.ends_with(b"TRUEVISION-XFILE.\0")); - let img = decode(&file, image::ImageFormat::Tga); + let img = decode(&file, craft_image_codecs::Format::Tga); assert_eq!(img.dimensions(), (w, h)); let want = on_white(px[(2 * w as usize + 3) * 4..][..4].try_into().unwrap()); let got = img.get_pixel(3, 2).0; diff --git a/crates/render/src/encode/tests_tiff.rs b/crates/render/src/encode/tests_tiff.rs index 380b6d155c..8665f8ded8 100644 --- a/crates/render/src/encode/tests_tiff.rs +++ b/crates/render/src/encode/tests_tiff.rs @@ -6,20 +6,20 @@ use craft_tiff::tags; use super::jpeg::ColorModel; use super::tiff::{self as t, ByteOrder, Compression, Image, Layout, Photometric, TiffOptions}; -fn ifd0(file: &[u8]) -> craft_tiff::reader::Ifd { +fn ifd0(file: &[u8]) -> craft_tiff::Ifd { Tiff::parse(file).expect("a TIFF").ifds.into_iter().next().expect("IFD0") } -fn tag_u16_vec(ifd: &craft_tiff::reader::Ifd, tag: u16) -> Option> { +fn tag_u16_vec(ifd: &craft_tiff::Ifd, tag: u16) -> Option> { ifd.value(tag).map(|v| v.to_u64_vec().into_iter().map(|x| x as u16).collect()) } -fn tag_u32_vec(ifd: &craft_tiff::reader::Ifd, tag: u16) -> Option> { +fn tag_u32_vec(ifd: &craft_tiff::Ifd, tag: u16) -> Option> { ifd.value(tag).map(|v| v.to_u64_vec().into_iter().map(|x| x as u32).collect()) } fn pixels(file: &[u8]) -> Vec { - craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, file).expect("decodes").data + craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, file).expect("decodes").into_data() } /// Straight RGBA: flat areas (as art is) with a transparent corner when `clear`. @@ -69,7 +69,7 @@ fn lzw_is_smaller_and_decodes_the_same() { assert_eq!(pixels(&lzw), px, "transparency kept as an alpha channel"); assert_eq!(pixels(&plain), px); let img = craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, &lzw).unwrap(); - assert_eq!(img.data, px); + assert_eq!(img.data(), px.as_slice()); } #[test] @@ -77,14 +77,14 @@ fn colour_models_write_their_samples() { let px = art(9, 6, true); let rgba = t::encode_samples(&px, 9, 6, 72.0, &opts(ColorModel::Rgb)).unwrap(); let rgba_ifd = ifd0(&rgba); - assert_eq!(rgba_ifd.u16(tags::PHOTOMETRIC_INTERPRETATION), Some(2)); + assert_eq!(rgba_ifd.u16(tags::PHOTOMETRIC), Some(2)); assert_eq!(rgba_ifd.u16(tags::SAMPLES_PER_PIXEL), Some(4)); assert_eq!(tag_u16_vec(&rgba_ifd, tags::BITS_PER_SAMPLE).as_deref(), Some([8, 8, 8, 8].as_slice())); assert_eq!(tag_u16_vec(&rgba_ifd, tags::EXTRA_SAMPLES).as_deref(), Some([2].as_slice()), "unassociated alpha"); let opaque = art(9, 6, false); let rgb = t::encode_samples(&opaque, 9, 6, 72.0, &opts(ColorModel::Rgb)).unwrap(); let rgb_ifd = ifd0(&rgb); - assert_eq!(rgb_ifd.u16(tags::PHOTOMETRIC_INTERPRETATION), Some(2)); + assert_eq!(rgb_ifd.u16(tags::PHOTOMETRIC), Some(2)); assert_eq!(rgb_ifd.u16(tags::SAMPLES_PER_PIXEL), Some(3)); assert!(rgb_ifd.value(tags::EXTRA_SAMPLES).is_none()); @@ -92,7 +92,7 @@ fn colour_models_write_their_samples() { let gray_ifd = ifd0(&gray); assert_eq!(gray_ifd.u16(tags::SAMPLES_PER_PIXEL), Some(1)); assert_eq!(tag_u16_vec(&gray_ifd, tags::BITS_PER_SAMPLE).as_deref(), Some([8].as_slice())); - assert_eq!(gray_ifd.u16(tags::PHOTOMETRIC_INTERPRETATION), Some(1), "black is zero"); + assert_eq!(gray_ifd.u16(tags::PHOTOMETRIC), Some(1), "black is zero"); let g = pixels(&gray); assert_eq!((g[0], g[8]), (super::jpeg::to_gray()([200, 30, 40]), 255), "lightness; white stays white"); let on_white = t::encode_samples(&px, 9, 6, 72.0, &opts(ColorModel::Gray)).unwrap(); @@ -105,10 +105,10 @@ fn colour_models_write_their_samples() { let cmyk = t::encode_samples(&inks, 9, 6, 72.0, &opts(ColorModel::Cmyk)).unwrap(); let d = ifd0(&cmyk); assert_eq!(d.u16(tags::SAMPLES_PER_PIXEL), Some(4)); - assert_eq!(d.u16(tags::PHOTOMETRIC_INTERPRETATION), Some(5), "separated"); + assert_eq!(d.u16(tags::PHOTOMETRIC), Some(5), "separated"); assert_eq!(d.u16(332), Some(1), "CMYK inks"); let cmyk_img = craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, &cmyk).unwrap(); - assert_eq!(cmyk_img.data, inks); + assert_eq!(cmyk_img.data(), inks.as_slice()); } #[test] @@ -118,7 +118,7 @@ fn resolution_tags_and_the_profile() { let file = t::encode_samples(&px, 4, 4, ppi, &opts(ColorModel::Rgb)).unwrap(); let d = ifd0(&file); for tag in [tags::X_RESOLUTION, tags::Y_RESOLUTION] { - let Some(craft_tiff::reader::IfdValue::Rationals(v)) = d.value(tag) else { panic!("rational") }; + let Some(craft_tiff::Value::Rationals(v)) = d.value(tag) else { panic!("rational") }; assert_eq!(v.as_slice(), &[rational]); } assert_eq!(d.u16(tags::RESOLUTION_UNIT), Some(2), "inches"); diff --git a/crates/render/src/encode/tests_web.rs b/crates/render/src/encode/tests_web.rs index e0e60037fe..10063a5da4 100644 --- a/crates/render/src/encode/tests_web.rs +++ b/crates/render/src/encode/tests_web.rs @@ -95,15 +95,75 @@ fn comments_are_valid_files() { let ix = quantize(&image(5, 4, |x, _| [x as u8 * 40, 0, 0]), 5, 4, &PaletteOptions::default()); let file = gif_comment(gif::encode(&ix, false).unwrap(), &"Copyright: Someone ".repeat(20)); assert!(file.windows(2).any(|w| w == [0x21, 0xFE])); - assert_eq!(image::load_from_memory(&file).unwrap().width(), 5); + assert_eq!( + craft_image_codecs::decode(&file) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .width(), + 5 + ); let px = vec![200u8; 5 * 4 * 3]; let jpg = jpeg::encode(&px, 5, 4, 80, Some(72.0), &jpeg::JpegOptions::default()).unwrap(); let with = jpeg_comment(jpg.clone(), "Copyright: Someone"); assert_eq!(with.len(), jpg.len() + 4 + 18); assert!(with.windows(2).any(|w| w == [0xFF, 0xFE])); - assert_eq!(image::load_from_memory(&with).unwrap().height(), 4); + assert_eq!( + craft_image_codecs::decode(&with) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .height(), + 4 + ); assert_eq!(jpeg_comment(vec![1, 2, 3], "x"), vec![1, 2, 3], "not a JPEG"); let png = png::with_srgb(png::encode(&[0, 0, 0, 255], 1, 1, &png::PngOptions::default()).unwrap()); assert!(png.windows(4).any(|w| w == b"sRGB")); - assert_eq!(image::load_from_memory(&png).unwrap().width(), 1); + assert_eq!( + craft_image_codecs::decode(&png) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .width(), + 1 + ); } diff --git a/crates/render/src/encode/tiff.rs b/crates/render/src/encode/tiff.rs index da8577c9b8..6a01f78109 100644 --- a/crates/render/src/encode/tiff.rs +++ b/crates/render/src/encode/tiff.rs @@ -192,12 +192,7 @@ pub fn write(img: &Image, l: &Layout) -> Result, String> { offsets.push(strips.len()); match l.compression { Compression::None => strips.extend_from_slice(strip), - Compression::Lzw => { - let lzw = weezl::encode::Encoder::with_tiff_size_switch(weezl::BitOrder::Msb, 8) - .encode(strip) - .map_err(|e| format!("TIFF encoding failed: {e}"))?; - strips.extend(lzw); - } + Compression::Lzw => strips.extend(craft_stream_codecs::lzw::encode(strip, true)), Compression::PackBits => strip.chunks(row).for_each(|r| packbits(r, &mut strips)), } // Strips start on a word boundary. diff --git a/crates/render/src/options.rs b/crates/render/src/options.rs index 7a9a9b81f2..2b540f0125 100644 --- a/crates/render/src/options.rs +++ b/crates/render/src/options.rs @@ -350,11 +350,16 @@ impl Rendered { /// Encode as PNG without metadata (thumbnails, screenshots, embedded rasters; exports use /// [`encode`]). pub fn to_png(&self) -> Result, String> { - let mut buf = Vec::new(); - let img = image::RgbaImage::from_raw(self.width, self.height, self.to_straight()) - .ok_or("PNG encoding failed: pixel buffer doesn't match the image size")?; - img.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png).map_err(|e| format!("PNG encoding failed: {e}"))?; - Ok(buf) + let img = craft_image_codecs::Image::from_raw( + self.width, + self.height, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + self.to_straight(), + ) + .map_err(|e| format!("PNG encoding failed: {e}"))?; + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map_err(|e| format!("PNG encoding failed: {e}")) } /// Each pixel's grey level and alpha: the Rec. 709 luma of its straight colour, with `bilevel` /// black below 128 and white from there up. A clear pixel is white: no ink where a fill diff --git a/crates/render/src/paint.rs b/crates/render/src/paint.rs index e51db9b251..39af072103 100644 --- a/crates/render/src/paint.rs +++ b/crates/render/src/paint.rs @@ -157,30 +157,63 @@ pub fn image_decodes() -> u64 { /// [`decode_in_room`]'s image or error. #[cfg(test)] -pub(crate) fn decode_within_allowance(bytes: &[u8]) -> image::ImageResult { +pub(crate) fn decode_within_allowance(bytes: &[u8]) -> Result { decode_in_room(bytes).map_err(|(e, _)| e) } +/// Probe `(width, height, total_bytes, bytes_per_pixel)` from headers where supported. +fn probe_header_info(format: craft_image_codecs::Format, bytes: &[u8]) -> Option<(u32, u32, u64, u64)> { + match format { + craft_image_codecs::Format::Png => { + let dec = craft_image_codecs::PngDecodeRows::new_streaming(bytes, &craft_image_codecs::Limits::default()).ok()?; + let h = dec.header(); + let bpp = u64::from(h.layout.channels() as u32) * u64::from(h.sample.bytes() as u32); + let total = u64::from(h.width).saturating_mul(u64::from(h.height)).saturating_mul(bpp); + Some((h.width, h.height, total, bpp)) + } + craft_image_codecs::Format::Jpeg => { + let info = craft_image_codecs::jpeg_info(bytes)?; + let bpp = u64::from(info.layout.channels() as u32); + let total = u64::from(info.width).saturating_mul(u64::from(info.height)).saturating_mul(bpp); + Some((info.width, info.height, total, bpp)) + } + craft_image_codecs::Format::Tiff => { + let info = craft_image_codecs::tiff_info(bytes).ok()?; + let p = info.pages.first()?; + let total = u64::from(p.width).saturating_mul(u64::from(p.height)).saturating_mul(4); + Some((p.width, p.height, total, 4)) + } + _ => { + let (w, h) = craft_image_codecs::probe_size(bytes).ok()?; + let total = u64::from(w).saturating_mul(u64::from(h)).saturating_mul(4); + Some((w, h, total, 4)) + } + } +} + /// `bytes` decoded within [`MAX_DECODE_ALLOC`], counted as RGBA: the image's size is read from its /// header first, and an image of more than that as RGBA gets a limit error before anything is /// decoded (#1717). A failure comes with why the image gave no pixels ([`room_for`]). -fn decode_in_room(bytes: &[u8]) -> Result { +fn decode_in_room(bytes: &[u8]) -> Result { let allowance = allowance(); - let unreadable = |e| (e, Undecoded::Unreadable); - let reader = || -> image::ImageResult<_> { - let mut r = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format()?; - let mut limits = image::Limits::default(); - limits.max_alloc = Some(allowance); - r.limits(limits); - Ok(r) - }; - let (w, h) = reader().and_then(|r| r.into_dimensions()).map_err(unreadable)?; - let bytes = (u64::from(w) * u64::from(h)).saturating_mul(4); - let pinned = crate::images::store().pinned_bytes() as u64; - if let Err(why) = room_for(bytes, pinned) { - return Err((image::ImageError::Limits(image::error::LimitError::from_kind(image::error::LimitErrorKind::InsufficientMemory)), why)); + let format = craft_image_codecs::detect(bytes).ok_or((craft_image_codecs::CodecError::UnknownFormat, Undecoded::Unreadable))?; + if let Some((w, h, _, _)) = probe_header_info(format, bytes) { + let rgba = (u64::from(w) * u64::from(h)).saturating_mul(4); + let pinned = crate::images::store().pinned_bytes() as u64; + if let Err(why) = room_for(rgba, pinned) { + return Err((craft_image_codecs::CodecError::LimitExceeded("decode allowance exceeded".into()), why)); + } } - reader().and_then(|r| r.decode()).map_err(unreadable) + let opts = craft_image_codecs::DecodeOptions { + limits: craft_image_codecs::Limits { max_alloc: Some(allowance), ..craft_image_codecs::Limits::default() }, + ..craft_image_codecs::DecodeOptions::default() + }; + let img = craft_image_codecs::decode_as_with(format, bytes, &opts).map_err(|e| (e, Undecoded::Unreadable))?; + let (w, h) = img.dimensions(); + let rgba = img.to_rgba8(); + image::RgbaImage::from_raw(w, h, rgba) + .map(image::DynamicImage::ImageRgba8) + .ok_or_else(|| (craft_image_codecs::CodecError::Decode("invalid image dimensions".into()), Undecoded::Unreadable)) } /// Whether an image of `rgba` bytes may be decoded while the images being painted hold `pinned` @@ -240,26 +273,21 @@ struct Reduction { /// [`reduced_size`]'s reading of `bytes` within `allowance`. fn reduction(bytes: &[u8], allowance: u64) -> Option { - use image::ImageDecoder as _; - let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?; - let format = reader.format()?; - if !matches!(format, image::ImageFormat::Png | image::ImageFormat::Jpeg | image::ImageFormat::Gif | image::ImageFormat::WebP) { + use craft_image_codecs::Format; + let format = craft_image_codecs::detect(bytes)?; + if !matches!(format, Format::Png | Format::Jpeg | Format::Gif | Format::WebP) { return None; } - let mut limits = image::Limits::default(); - limits.max_alloc = Some(allowance); - reader.limits(limits); - let d = reader.into_decoder().ok()?; - let (w, h) = d.dimensions(); + let (w, h, total_bytes, bpp) = probe_header_info(format, bytes)?; let pixels = u64::from(w) * u64::from(h); // An image of more pixels than the allowance has bytes (four times what it holds as RGBA) is // not read. - if pixels == 0 || pixels > allowance || (pixels.saturating_mul(4) <= allowance && d.total_bytes() <= allowance) { + if pixels == 0 || pixels > allowance || (pixels.saturating_mul(4) <= allowance && total_bytes <= allowance) { return None; } let to = fitted_dims(w, h, allowance)?; // A PNG that isn't interlaced or animated (and upright in pre-pixel EXIF) is read a row at a time when the reader's buffers fit the allowance. - let row_scratch = if format == image::ImageFormat::Png { + let row_scratch = if format == Format::Png { craft_image_codecs::PngDecodeRows::new_streaming(bytes, &craft_image_codecs::Limits::default()) .ok() .filter(|dec| dec.streamable()) @@ -270,10 +298,10 @@ fn reduction(bytes: &[u8], allowance: u64) -> Option { }; let rows = row_scratch.is_some(); let scratch = row_scratch.unwrap_or_else(|| { - let band = u64::from(BAND) * u64::from(w) * (u64::from(d.color_type().bytes_per_pixel()) + 4); - d.total_bytes().saturating_add(band) + let band = u64::from(BAND) * u64::from(w) * (bpp + 4); + total_bytes.saturating_add(band) }); - (rows || d.total_bytes() <= allowance).then_some(Reduction { size: (w, h), to, rows, scratch }) + (rows || total_bytes <= allowance).then_some(Reduction { size: (w, h), to, rows, scratch }) } /// How many rows of an image decoded whole [`reduced_pixmap`] converts to RGBA at a time. @@ -294,9 +322,7 @@ const PNG_WINDOW_AND_STEP: u64 = (32 << 10) + (8 << 10); /// to twice the size it holds, are both allocated: three times that size at most. A copy of a /// stored row and the row given out come on top. `None` when a row given out doesn't fit memory. fn png_row_scratch(hdr: &craft_image_codecs::PngHeader) -> Option { - let out = u64::from(hdr.width) - .checked_mul(u64::from(hdr.layout.channels()))? - .checked_mul(u64::from(hdr.sample.bytes()))?; + let out = u64::from(hdr.width).checked_mul(hdr.layout.channels() as u64)?.checked_mul(hdr.sample.bytes() as u64)?; // A filter byte and the row's samples. let stored = 1u64.checked_add(out)?; let kept = (stored * 4).next_multiple_of(64).max(PNG_KEPT_ROWS); @@ -343,59 +369,51 @@ fn shrunk(bytes: &[u8], r: &Reduction) -> Option { dec.step_stream::(1, &mut || true, &mut |_y, row| { match (hdr.layout, hdr.sample) { (ChannelLayout::Gray, SampleType::U8) => shrink.row(row.iter().map(|&g| [g, g, g, 255])), - (ChannelLayout::GrayA, SampleType::U8) => { - shrink.row(row.as_chunks::<2>().0.iter().map(|&[g, a]| [g, g, g, a])) - } - (ChannelLayout::Rgb, SampleType::U8) => { - shrink.row(row.as_chunks::<3>().0.iter().map(|&[r, g, b]| [r, g, b, 255])) - } + (ChannelLayout::GrayA, SampleType::U8) => shrink.row(row.as_chunks::<2>().0.iter().map(|&[g, a]| [g, g, g, a])), + (ChannelLayout::Rgb, SampleType::U8) => shrink.row(row.as_chunks::<3>().0.iter().map(|&[r, g, b]| [r, g, b, 255])), (ChannelLayout::Rgba, SampleType::U8) => shrink.row(row.as_chunks::<4>().0.iter().copied()), (ChannelLayout::Gray, SampleType::U16) => shrink.row(row.as_chunks::<2>().0.iter().map(|&g| { let v = (u16::from_ne_bytes(g) >> 8) as u8; [v, v, v, 255] })), - (ChannelLayout::GrayA, SampleType::U16) => { - shrink.row(row.as_chunks::<4>().0.iter().map(|&[g0, g1, a0, a1]| { - let g = (u16::from_ne_bytes([g0, g1]) >> 8) as u8; - let a = (u16::from_ne_bytes([a0, a1]) >> 8) as u8; - [g, g, g, a] - })) + (ChannelLayout::GrayA, SampleType::U16) => shrink.row(row.as_chunks::<4>().0.iter().map(|&[g0, g1, a0, a1]| { + let g = (u16::from_ne_bytes([g0, g1]) >> 8) as u8; + let a = (u16::from_ne_bytes([a0, a1]) >> 8) as u8; + [g, g, g, a] + })), + (ChannelLayout::Rgb, SampleType::U16) => shrink.row(row.as_chunks::<6>().0.iter().map(|&[r0, r1, g0, g1, b0, b1]| { + [ + (u16::from_ne_bytes([r0, r1]) >> 8) as u8, + (u16::from_ne_bytes([g0, g1]) >> 8) as u8, + (u16::from_ne_bytes([b0, b1]) >> 8) as u8, + 255, + ] + })), + (ChannelLayout::Rgba, SampleType::U16) => shrink.row(row.as_chunks::<8>().0.iter().map(|&[r0, r1, g0, g1, b0, b1, a0, a1]| { + [ + (u16::from_ne_bytes([r0, r1]) >> 8) as u8, + (u16::from_ne_bytes([g0, g1]) >> 8) as u8, + (u16::from_ne_bytes([b0, b1]) >> 8) as u8, + (u16::from_ne_bytes([a0, a1]) >> 8) as u8, + ] + })), + _ => { + return Err(CodecError::Unsupported { format: Format::Png, reason: "unsupported PNG channel layout".into() }); } - (ChannelLayout::Rgb, SampleType::U16) => { - shrink.row(row.as_chunks::<6>().0.iter().map(|&[r0, r1, g0, g1, b0, b1]| { - [ - (u16::from_ne_bytes([r0, r1]) >> 8) as u8, - (u16::from_ne_bytes([g0, g1]) >> 8) as u8, - (u16::from_ne_bytes([b0, b1]) >> 8) as u8, - 255, - ] - })) - } - (ChannelLayout::Rgba, SampleType::U16) => { - shrink.row(row.as_chunks::<8>().0.iter().map(|&[r0, r1, g0, g1, b0, b1, a0, a1]| { - [ - (u16::from_ne_bytes([r0, r1]) >> 8) as u8, - (u16::from_ne_bytes([g0, g1]) >> 8) as u8, - (u16::from_ne_bytes([b0, b1]) >> 8) as u8, - (u16::from_ne_bytes([a0, a1]) >> 8) as u8, - ] - })) - } - _ => return Err(CodecError::unsupported(Format::Png, "unsupported PNG channel layout")), } Ok(()) }) .ok()??; } else { - let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?; - let mut limits = image::Limits::default(); - limits.max_alloc = Some(allowance()); - reader.limits(limits); - let img = reader.decode().ok()?; - let (w, h) = (img.width(), img.height()); - for y in (0..h).step_by(BAND as usize) { - let band = img.crop_imm(0, y, w, BAND.min(h - y)).to_rgba8(); - band.as_raw().as_chunks::<4>().0.chunks_exact(w as usize).for_each(|row| shrink.row(row.iter().copied())); + let opts = craft_image_codecs::DecodeOptions { + limits: craft_image_codecs::Limits { max_alloc: Some(allowance()), ..craft_image_codecs::Limits::default() }, + ..craft_image_codecs::DecodeOptions::default() + }; + let img = craft_image_codecs::decode_with(bytes, &opts).ok()?; + let (w, _) = img.dimensions(); + let rgba = img.to_rgba8(); + for row in rgba.as_chunks::<4>().0.chunks_exact(w as usize) { + shrink.row(row.iter().copied()); } } shrink.finish() @@ -511,7 +529,9 @@ fn decode_or_reduction(bytes: &[u8]) -> Result Ok(img), - Err((image::ImageError::Limits(_), Undecoded::Unreadable)) => Err(reduction(bytes, allowance()).ok_or(Undecoded::Unreadable)), + Err((craft_image_codecs::CodecError::LimitExceeded(_), Undecoded::Unreadable)) => { + Err(reduction(bytes, allowance()).ok_or(Undecoded::Unreadable)) + } Err((_, why)) => Err(Err(why)), } } @@ -641,8 +661,16 @@ mod tests { /// clear pixels beside them do not darken them. #[test] fn an_image_drawn_smaller_keeps_its_color_beside_clear_pixels() { - let mut png = Vec::new(); - striped(8).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let s = striped(8); + let img = craft_image_codecs::Image::from_raw( + s.width(), + s.height(), + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + s.into_raw(), + ) + .unwrap(); + let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); let pm = decode_pixmap_fit(&png, 2, 1).unwrap(); assert_eq!((pm.width(), pm.height()), (2, 1)); assert!(pm.data().iter().all(|p| p.a > 0)); diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 99fa434ca3..457f06549c 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -694,7 +694,41 @@ fn trace_source_draws_the_source_image_of_the_listed_objects() { use vectorcraft_doc::{ImageBlob, ImageObject}; let img = image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255])); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let mut d = Document::new(100.0, 100.0); d.images.insert("red".into(), ImageBlob::new("image/png", png)); // A group at `x`: the hidden red source image, then a blue traced square over it. @@ -742,7 +776,41 @@ fn trace_source_applies_the_hidden_image_mask() { use vectorcraft_doc::{ImageBlob, ImageObject, NodeKind, OpacityMask}; let mut png = Vec::new(); - image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255]))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let mut d = Document::new(100.0, 100.0); d.images.insert("trace-source".into(), ImageBlob::new("image/png", png)); let image = ImageObject { @@ -1125,9 +1193,42 @@ fn complete_image_mask_with_blur_reuses_cached_raster() { use vectorcraft_doc::{Effect, ImageBlob, ImageObject, NodeKind, OpacityMask}; let mut png = Vec::new(); - image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(20, 20, image::Rgba([255, 255, 255, 255]))) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = + (image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(20, 20, image::Rgba([255, 255, 255, 255])))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let mut d = Document::new(100.0, 100.0); d.images.insert("complete-mask-image".into(), ImageBlob::new("image/png", png)); let image = ImageObject { @@ -1506,10 +1607,63 @@ fn a_kept_decoded_image_is_drawn_without_decoding_it() { // them are partly transparent. let img = image::RgbaImage::from_fn(37, 23, |x, y| image::Rgba([(x * 7) as u8, (y * 11) as u8, 99, if (x + y) % 2 == 0 { 255 } else { 77 }])); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let blob = ImageBlob::new("image/png", png.clone()); assert!(!image_cached(&blob)); - assert!(keep_decoded_image(&blob, image::load_from_memory(&png).unwrap())); + assert!(keep_decoded_image( + &blob, + craft_image_codecs::decode(&png) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + )); assert!(image_cached(&blob)); let key = blobs::blob_key(&blob).0; let kept = images::store().peek(&key).unwrap(); @@ -1550,7 +1704,41 @@ fn images_take_their_nearest_pixel_without_smoothing() { use vectorcraft_doc::{ImageBlob, ImageObject, NodeKind}; let img = image::RgbaImage::from_fn(2, 1, |x, _| image::Rgba(if x == 0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] })); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let mut d = Document::new(40.0, 20.0); d.images.insert("bw".into(), ImageBlob::new("image/png", png)); let id = d.alloc_id(); @@ -1575,7 +1763,41 @@ fn an_image_masked_by_a_white_shape_draws_as_if_clipped() { use vectorcraft_doc::{ImageBlob, ImageObject, NodeKind, OpacityMask}; let img = image::RgbaImage::from_pixel(2, 2, image::Rgba([255, 0, 0, 255])); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let doc_masked = |mask_color: Color, shape: Rect| { let mut d = Document::new(100.0, 100.0); d.images.insert("red".into(), ImageBlob::new("image/png", png.clone())); @@ -1630,7 +1852,41 @@ fn a_pixelated_image_draws_reduced_without_mips() { use vectorcraft_doc::{ImageBlob, ImageObject, NodeKind}; let img = image::RgbaImage::from_fn(64, 64, |x, y| image::Rgba(if (x + y) % 2 == 0 { [255, 0, 0, 255] } else { [0, 0, 255, 255] })); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let mut d = Document::new(64.0, 64.0); d.images.insert("check".into(), ImageBlob::new("image/png", png)); let id = d.alloc_id(); @@ -1686,16 +1942,16 @@ fn tiff_header(w: u32, h: u32) -> Vec { #[test] fn an_image_too_large_as_rgba_is_not_decoded() { let over = paint::decode_within_allowance(&png_header(23_171, 23_170)); - assert!(matches!(over, Err(image::ImageError::Limits(_))), "{over:?}"); + assert!(matches!(over, Err(craft_image_codecs::CodecError::LimitExceeded(_))), "{over:?}"); let failed = decode_failures(); assert!(paint::decode_pixmap(&png_header(23_171, 23_170)).is_none()); assert!(decode_failures() > failed); // Within the allowance: decoded, and its missing rows can't be read. let within = paint::decode_within_allowance(&png_header(23_170, 23_170)); - assert!(matches!(within, Err(image::ImageError::Decoding(_))), "{within:?}"); + assert!(matches!(within, Err(craft_image_codecs::CodecError::Decode(_))), "{within:?}"); // A header whose size as RGBA does not fit in 64 bits gets the same limit error. let huge = paint::decode_within_allowance(&tiff_header(1 << 31, 1 << 31)); - assert!(matches!(huge, Err(image::ImageError::Limits(_))), "{huge:?}"); + assert!(matches!(huge, Err(craft_image_codecs::CodecError::LimitExceeded(_))), "{huge:?}"); } /// A PNG of `w` × `h` noisy pixels cut off halfway through its bytes: its header reads, and its @@ -1706,7 +1962,41 @@ fn truncated_png(w: u32, h: u32) -> Vec { image::Rgba([v[0], v[1], v[2], 255]) }); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); png.truncate(png.len() / 2); png } @@ -1718,7 +2008,7 @@ fn truncated_png(w: u32, h: u32) -> Vec { fn an_undecodable_image_is_tried_once_and_marked_on_screen() { use vectorcraft_doc::{ImageBlob, ImageObject, NodeKind}; let png = truncated_png(61, 47); - assert_eq!(image::ImageReader::new(std::io::Cursor::new(&png)).with_guessed_format().unwrap().into_dimensions().unwrap(), (61, 47)); + assert_eq!(craft_image_codecs::decode(&png).unwrap().dimensions(), (61, 47)); let mut d = Document::new(80.0, 60.0); d.images.insert("cut".into(), ImageBlob::new("image/png", png)); let id = d.alloc_id(); @@ -1823,7 +2113,41 @@ fn a_gray_image_draws_its_gray_levels() { use vectorcraft_doc::{ImageBlob, ImageObject, NodeKind}; let img = image::GrayImage::from_fn(2, 1, |x, _| image::Luma([if x == 0 { 40 } else { 200 }])); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let mut d = Document::new(40.0, 20.0); d.images.insert("gray".into(), ImageBlob::new("image/png", png)); let id = d.alloc_id(); @@ -1843,9 +2167,42 @@ fn with_allowance(bytes: u64, f: impl FnOnce() -> T) -> T { } /// `img` encoded as `format`. -fn encoded(img: image::DynamicImage, format: image::ImageFormat) -> Vec { +fn encoded(img: image::DynamicImage, format: craft_image_codecs::Format) -> Vec { let mut out = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut out), format).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, format, &craft_image_codecs::EncodeOptions::default()).map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); out } @@ -1857,7 +2214,7 @@ fn a_png_past_the_allowance_draws_at_reduced_size() { let img = image::ImageBuffer::, _>::from_fn(400, 400, |x, _| { if x < 200 { image::Rgba([51400, 10280, 10280, 65535]) } else { image::Rgba([10280, 10280, 51400, 65535]) } }); - let png = encoded(image::DynamicImage::ImageRgba16(img), image::ImageFormat::Png); + let png = encoded(image::DynamicImage::ImageRgba16(img), craft_image_codecs::Format::Png); // 400 × 400 is 640,000 bytes as RGBA; 387 × 387 is the largest within 600,000. assert_eq!(with_allowance(600_000, || paint::reduced_size(&png)), Some((387, 387))); assert_eq!(paint::reduced_size(&png), None, "within the 2 GB allowance"); @@ -1876,7 +2233,7 @@ fn a_png_past_the_allowance_draws_at_reduced_size() { // 300 × 300 at 16 bits a sample is 720,000 bytes decoded and 360,000 as RGBA: past 600,000 as // decoded and within it as RGBA, it is read a row at a time at its own size. let small = image::ImageBuffer::, _>::from_pixel(300, 300, image::Rgba([51400, 10280, 10280, 65535])); - let small = encoded(image::DynamicImage::ImageRgba16(small), image::ImageFormat::Png); + let small = encoded(image::DynamicImage::ImageRgba16(small), craft_image_codecs::Format::Png); assert_eq!(with_allowance(600_000, || paint::reduced_size(&small)), Some((300, 300))); let pm = with_allowance(600_000, || paint::decode_pixmap(&small)).expect("read a row at a time"); let c = pm.sample(3, 3); @@ -1887,13 +2244,14 @@ fn a_png_past_the_allowance_draws_at_reduced_size() { // take 600,043 and are not decoded (their samples, 8 bytes a pixel, are past it too). let wide = |w: u32| { let img = image::ImageBuffer::, _>::from_pixel(w, 60, image::Rgba([51400, 10280, 10280, 65535])); - encoded(image::DynamicImage::ImageRgba16(img), image::ImageFormat::Png) + encoded(image::DynamicImage::ImageRgba16(img), craft_image_codecs::Format::Png) }; assert_eq!(with_allowance(600_000, || paint::reduced_size(&wide(1398))), Some((1398, 60))); assert_eq!(with_allowance(600_000, || paint::reduced_size(&wide(1399))), None); // An image of more pixels than the allowance has bytes is not read: 1,000 × 400 8-bit gray // pixels are drawn at 500 × 200 within 400,000 bytes, and 1,000 × 401 are not. - let gray = |h: u32| encoded(image::DynamicImage::ImageLuma8(image::GrayImage::from_pixel(1000, h, image::Luma([90]))), image::ImageFormat::Png); + let gray = + |h: u32| encoded(image::DynamicImage::ImageLuma8(image::GrayImage::from_pixel(1000, h, image::Luma([90]))), craft_image_codecs::Format::Png); assert_eq!(with_allowance(400_000, || paint::reduced_size(&gray(400))), Some((500, 200))); assert_eq!(with_allowance(400_000, || paint::reduced_size(&gray(401))), None); } @@ -1904,7 +2262,8 @@ fn a_png_past_the_allowance_draws_at_reduced_size() { /// noted as undecodable. #[test] fn a_jpeg_past_the_allowance_as_rgba_is_shrunk_and_a_gif_past_it_is_not_decoded() { - let jpeg = encoded(image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(80, 60, image::Rgb([30, 120, 200]))), image::ImageFormat::Jpeg); + let jpeg = + encoded(image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(80, 60, image::Rgb([30, 120, 200]))), craft_image_codecs::Format::Jpeg); // 14,400 bytes of RGB, 19,200 as RGBA: 73 × 54 is the largest within 16,000. let pm = with_allowance(16_000, || paint::decode_pixmap(&jpeg)).expect("decoded at reduced size"); assert_eq!((pm.width(), pm.height()), (73, 54)); @@ -1913,8 +2272,10 @@ fn a_jpeg_past_the_allowance_as_rgba_is_shrunk_and_a_gif_past_it_is_not_decoded( // A placed document's preview asks for 20 × 15: decoded straight at that size. let pm = with_allowance(16_000, || paint::decode_pixmap_fit(&jpeg, 20, 15)).expect("decoded at the size asked for"); assert_eq!((pm.width(), pm.height()), (20, 15)); - let gif = - encoded(image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(80, 60, image::Rgba([30, 120, 200, 255]))), image::ImageFormat::Gif); + let gif = encoded( + image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(80, 60, image::Rgba([30, 120, 200, 255]))), + craft_image_codecs::Format::Gif, + ); assert_eq!(with_allowance(16_000, || paint::reduced_size(&gif)), None); let failed = decode_failures(); let why = with_allowance(16_000, || paint::decode_pixmap_or_why(&gif)).err(); @@ -1937,12 +2298,13 @@ fn a_reduced_decode_counts_what_reading_takes_beside_the_images_paints_hold() { } // Decoded whole: 14,400 bytes of RGB and a 16-row band of 8,960 bytes, beside a 73 × 54 result // of 15,768 bytes. - let jpeg = encoded(image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(80, 60, image::Rgb([30, 120, 200]))), image::ImageFormat::Jpeg); + let jpeg = + encoded(image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(80, 60, image::Rgb([30, 120, 200]))), craft_image_codecs::Format::Jpeg); // Read a row at a time: 540,103 bytes in the reader's buffers for 400 columns of 16-bit RGBA, // beside a 387 × 387 result of 599,076 bytes. let png = encoded( image::DynamicImage::ImageRgba16(image::ImageBuffer::from_pixel(400, 400, image::Rgba([51400, 10280, 10280, 65535]))), - image::ImageFormat::Png, + craft_image_codecs::Format::Png, ); for (bytes, allowance, room, size) in [(&jpeg, 16_000, 15_768 + 14_400 + 8_960, (73, 54)), (&png, 600_000, 599_076 + 540_103, (387, 387))] { let failed = decode_failures(); diff --git a/crates/render/src/tests/adjust.rs b/crates/render/src/tests/adjust.rs index c50bdc39f4..ba138034a3 100644 --- a/crates/render/src/tests/adjust.rs +++ b/crates/render/src/tests/adjust.rs @@ -47,7 +47,41 @@ fn red_square(x: f64, y: f64) -> Node { fn red_image() -> (String, ImageBlob) { let img = image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255])); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); ("red".into(), ImageBlob::new("image/png", png)) } diff --git a/crates/render/src/tests/changed.rs b/crates/render/src/tests/changed.rs index 27c299c49c..c62b6864c2 100644 --- a/crates/render/src/tests/changed.rs +++ b/crates/render/src/tests/changed.rs @@ -547,7 +547,41 @@ fn traced(view: &str) -> (Document, NodeId, NodeId, NodeId) { let mut d = Document::new(W as f64, H as f64); let mut png = vec![]; let red = image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255])); - red.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (red).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); d.images.insert("red".into(), vectorcraft_doc::ImageBlob::new("image/png", png)); let source = red_image(&mut d, 10.0); let a = rect(&mut d, Rect::new(60.0, 10.0, 70.0, 20.0), Color::rgb(0.0, 0.5, 0.0)); diff --git a/crates/render/src/tests/cmykblend.rs b/crates/render/src/tests/cmykblend.rs index 2235320021..afc37ea207 100644 --- a/crates/render/src/tests/cmykblend.rs +++ b/crates/render/src/tests/cmykblend.rs @@ -211,7 +211,41 @@ fn placed_images_are_separated_not_blackened() { let mut d = doc(ColorMode::Cmyk, None, CYAN, Blend::Normal, 0.5); let img = image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, 255])); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); d.images.insert("red".into(), ImageBlob::new("image/png", png)); let n = Node::new( d.alloc_id(), @@ -255,7 +289,41 @@ fn rich_black_shows_black_ink_alone_as_rgb_black() { let mut d = Document::new_with_mode(20.0, 20.0, ColorMode::Cmyk); let img = image::RgbaImage::from_pixel(20, 20, image::Rgba([255, 0, 0, 255])); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); d.images.insert("red".into(), ImageBlob::new("image/png", png)); let im = ImageObject { key: "red".into(), width: 20, height: 20, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; let n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))); diff --git a/crates/render/src/tests/colorize.rs b/crates/render/src/tests/colorize.rs index 8a8891c7da..acf7154af1 100644 --- a/crates/render/src/tests/colorize.rs +++ b/crates/render/src/tests/colorize.rs @@ -28,7 +28,41 @@ fn bilevel_tiff() -> Vec { fn gray_png() -> Vec { let img = image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap(); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); png } @@ -81,7 +115,41 @@ fn gray_and_1_bit_images_draw_in_their_spot_color_with_white_transparent() { fn shrunk_copies_are_kept_per_color() { let black = image::GrayImage::from_raw(64, 64, vec![0; 64 * 64]).unwrap(); let mut png = vec![]; - black.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (black).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let blob = ImageBlob::new("image/png", png); let d = doc_of(blob.clone(), Some(Paint::solid(Color::rgb(0.0, 0.0, 1.0))), (64, 64), 1.0); let plain = doc_of(blob, None, (64, 64), 1.0); @@ -102,7 +170,41 @@ fn shrunk_copies_are_kept_per_color() { fn kept_images_only_draw_the_colorized_pixels() { let black = image::GrayImage::from_raw(48, 48, vec![0; 48 * 48]).unwrap(); let mut png = vec![]; - black.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (black).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let d = doc_of(ImageBlob::new("image/png", png), Some(Paint::solid(Color::rgb(0.0, 0.0, 1.0))), (48, 48), 1.0); let view = Affine::scale(0.25); let mut r = Renderer::new(); @@ -135,7 +237,41 @@ fn ink_planes_keep_the_colors_own_inks() { fn colorize_dims_with_the_grays() { let gray = image::GrayImage::from_raw(2, 1, vec![128, 255]).unwrap(); let mut png = vec![]; - gray.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (gray).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let d = doc(ImageBlob::new("image/png", png), Some(Paint::solid(Color::rgb(0.0, 0.0, 1.0)))); let px = Renderer::new().render(&d, 40, 20, Affine::IDENTITY, &RenderOptions { smooth_images: false, ..Default::default() }).pixel(10, 10); // Half blue over the green band. @@ -346,7 +482,41 @@ fn image_and_fills(mode: vectorcraft_doc::ColorMode, blob: ImageBlob, (width, he fn rgb_png(width: u32, height: u32, pixels: &[[u8; 3]]) -> Vec { let img = image::RgbImage::from_raw(width, height, pixels.concat()).unwrap(); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); png } diff --git a/crates/render/src/tests/container.rs b/crates/render/src/tests/container.rs index dfc8dca91c..30266547af 100644 --- a/crates/render/src/tests/container.rs +++ b/crates/render/src/tests/container.rs @@ -155,7 +155,41 @@ fn group_geometry_effects_move_the_members_as_one_piece() { fn group_geometry_effects_move_and_copy_images_too() { let mut d = Document::new(100.0, 100.0); let mut png = Vec::new(); - image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, 255]))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); d.images.insert("red".into(), ImageBlob::new("image/png", png)); let b = rect(&mut d, Rect::new(0.0, 0.0, 20.0, 20.0), solid(0.0, 0.0, 1.0)); let im = ImageObject { diff --git a/crates/render/src/tests/layeropts.rs b/crates/render/src/tests/layeropts.rs index bfa7910f15..7fb585c372 100644 --- a/crates/render/src/tests/layeropts.rs +++ b/crates/render/src/tests/layeropts.rs @@ -12,7 +12,41 @@ fn doc(layer: impl FnOnce(&mut NodeKind)) -> Document { let mut d = Document::new(100.0, 100.0); let img = image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255])); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); d.images.insert("red".into(), ImageBlob::new("image/png", png)); let l = d.layers[0].id; let red = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); diff --git a/crates/render/src/tests/memory.rs b/crates/render/src/tests/memory.rs index a9226da834..93b4361771 100644 --- a/crates/render/src/tests/memory.rs +++ b/crates/render/src/tests/memory.rs @@ -18,7 +18,41 @@ fn png(w: u32, h: u32, seed: u8) -> Vec { image::Rgba([v ^ seed, v.wrapping_mul(3), seed, 255]) }); let mut out = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); out } @@ -2536,7 +2570,41 @@ fn a_reduced_image_on_the_ink_planes_shows_its_average() { let _fonts = fonts_steady(); let lines = image::RgbaImage::from_fn(64, 64, |x, _| image::Rgba(if x % 2 == 0 { [0, 0, 0, 255] } else { [255; 4] })); let mut bytes = vec![]; - lines.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (lines).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| bytes.extend_from_slice(&__b)) + } + .unwrap(); let mut d = cmyk_doc_with("lines", ImageBlob::new("image/png", bytes), 64, 64); // Transparency beside the image: the document blends in CMYK, drawing on its ink planes. let shape = vectorcraft_geom::shapes::rectangle(Rect::new(100.0, 0.0, 110.0, 10.0)); @@ -2560,7 +2628,41 @@ fn a_reduced_image_on_the_ink_planes_shows_its_average() { fn varied_png(w: u32, h: u32, seed: u8) -> Vec { let img = image::RgbaImage::from_fn(w, h, |x, y| image::Rgba([(x * 5 + y) as u8, (x / 3 + y * 7) as u8, (x ^ y) as u8 ^ seed, 255])); let mut out = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); out } diff --git a/crates/render/src/tests/meshwarp.rs b/crates/render/src/tests/meshwarp.rs index d4e5a98499..7f3992c4b5 100644 --- a/crates/render/src/tests/meshwarp.rs +++ b/crates/render/src/tests/meshwarp.rs @@ -10,7 +10,41 @@ use vectorcraft_geom::Point; fn png(alpha: u8) -> Vec { let img = image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, alpha])); let mut out = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); out } diff --git a/crates/render/src/tests/objectfx.rs b/crates/render/src/tests/objectfx.rs index c359f65219..b609ac56c6 100644 --- a/crates/render/src/tests/objectfx.rs +++ b/crates/render/src/tests/objectfx.rs @@ -306,7 +306,41 @@ fn image_doc(effects: Vec) -> Document { let mut d = Document::new(100.0, 100.0); let img = image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255])); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); d.images.insert("red".into(), ImageBlob::new("image/png", png)); let mut n = Node::new( NodeId(0), @@ -786,7 +820,41 @@ fn an_images_outline_object_stroke_follows_new_pixels_under_the_same_key() { image::Rgba([255, 0, 0, if r <= 8.0 { 255 } else { 0 }]) }); let mut png = vec![]; - disc.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (disc).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); d.images.insert("red".into(), ImageBlob::new("image/png", png)); let img = r.render(&d, 100, 100, Affine::IDENTITY, &opts); assert_eq!((lum(img.pixel(19, 35)), lum(img.pixel(26, 35))), (WHITE, 0)); diff --git a/crates/render/src/tests/placed_document.rs b/crates/render/src/tests/placed_document.rs index 3a65b1abe0..85e3b1ecb1 100644 --- a/crates/render/src/tests/placed_document.rs +++ b/crates/render/src/tests/placed_document.rs @@ -374,7 +374,41 @@ fn a_placed_document_kept_as_its_preview_draws_the_preview() { // Only the preview (a 20×10 green PNG) is there, and the file can't be read here. let img = image::RgbaImage::from_pixel(20, 10, image::Rgba([0, 200, 0, 255])); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let mut blob = ImageBlob::new("image/png", png); blob.proxy = Some(blob.bytes.clone()); d.images.insert("preview-1".into(), blob); diff --git a/crates/render/src/tests/setup.rs b/crates/render/src/tests/setup.rs index e80e807e4a..ffaccf832f 100644 --- a/crates/render/src/tests/setup.rs +++ b/crates/render/src/tests/setup.rs @@ -7,7 +7,41 @@ use crate::*; fn doc_with_red_image() -> Document { let mut d = Document::new(40.0, 40.0); let mut png = Vec::new(); - image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, 255]))).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); d.images.insert("red".into(), ImageBlob::new("image/png", png)); let (id, layer) = (d.alloc_id(), d.layers[0].id); let im = ImageObject { key: "red".into(), width: 40, height: 40, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; diff --git a/crates/render/src/tests/viewraster.rs b/crates/render/src/tests/viewraster.rs index 47fd4d9461..b32ea5225e 100644 --- a/crates/render/src/tests/viewraster.rs +++ b/crates/render/src/tests/viewraster.rs @@ -115,7 +115,41 @@ fn rasters_cropped_to_the_view_follow_a_pan_and_a_zoom() { fn large_image(effects: &[(&str, serde_json::Value)]) -> Document { let img = image::RgbaImage::from_fn(300, 200, |x, y| image::Rgba([(x * 7) as u8, (y * 13) as u8, ((x + y) * 3) as u8, 255])); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (img).into(); + let (__w, __h) = (__dyn.width(), __dyn.height()); + let (__layout, __sample, __raw) = match __dyn { + image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()), + image::DynamicImage::ImageLuma16(b) => ( + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageLumaA16(b) => ( + craft_image_codecs::ChannelLayout::GrayA, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgb16(b) => ( + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + image::DynamicImage::ImageRgba16(b) => ( + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U16, + b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(), + ), + other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()), + }; + let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap(); + craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.extend_from_slice(&__b)) + } + .unwrap(); let mut d = Document::new(6000.0, 4000.0); d.images.insert("viewraster-pan".into(), ImageBlob::new("image/png", png)); let im = ImageObject { diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index 36744c8de5..2665544f84 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -20,7 +20,6 @@ vectorcraft-brush = { workspace = true } vectorcraft-text = { workspace = true } vectorcraft-pathops = { workspace = true } kurbo = { workspace = true } -usvg = { workspace = true } thiserror = { workspace = true } serde = { workspace = true } # Live effect params read from filters. @@ -28,6 +27,7 @@ serde_json = { workspace = true } # SVGZ (gzip, pure-Rust backend: builds for wasm). flate2 = { workspace = true } image = { workspace = true } +craft-image-codecs = { workspace = true } # Colour / transform / length parsing for the fallback (MIT OR Apache-2.0; already used by usvg). svgtypes = "0.16" simplecss = "0.2.2" @@ -39,9 +39,6 @@ unicode-bidi = "0.3.18" skrifa = { workspace = true } # A variable font built in code (no font file is committed). vectorcraft-text = { workspace = true, features = ["test-fonts"] } -resvg = { version = "0.45", default-features = false, features = ["raster-images"] } -# usvg as a reference viewer that lays text out in a font (text_layout.rs). -usvg = { workspace = true, features = ["text"] } +craft-svg = { workspace = true, features = ["tree-render", "tree-text"] } vectorcraft-testkit = { workspace = true } proptest = { workspace = true } -image = { workspace = true } diff --git a/crates/svg/src/export.rs b/crates/svg/src/export.rs index 05107bfb65..42dd233914 100644 --- a/crates/svg/src/export.rs +++ b/crates/svg/src/export.rs @@ -1,5 +1,6 @@ //! The SVG writer. +use craft_svg::tree::usvg; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::fmt::Write as _; use std::sync::Arc; diff --git a/crates/svg/src/export/paint.rs b/crates/svg/src/export/paint.rs index bedf456f11..89a6c2f48c 100644 --- a/crates/svg/src/export/paint.rs +++ b/crates/svg/src/export/paint.rs @@ -13,10 +13,16 @@ fn web_image(b: &ImageBlob) -> std::borrow::Cow<'_, ImageBlob> { if matches!(b.mime.as_str(), "image/png" | "image/jpeg" | "image/jpg" | "image/gif" | "image/webp" | "image/svg+xml") { return Cow::Borrowed(b); } - let png = image::load_from_memory(&b.bytes).ok().and_then(|img| { - let mut out = Vec::new(); - img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).ok()?; - Some(out) + let png = craft_image_codecs::decode(&b.bytes).ok().and_then(|img| { + let raw = craft_image_codecs::Image::from_raw( + img.width(), + img.height(), + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + img.to_rgba8(), + ) + .ok()?; + craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok() }); png.map_or(Cow::Borrowed(b), |png| Cow::Owned(ImageBlob::png(png))) } @@ -81,15 +87,16 @@ impl Writer<'_> { for alpha in coverage { rgba.extend_from_slice(&if self.tiny() { [rgb[0], rgb[1], rgb[2], alpha] } else { [255, 255, 255, alpha] }); } - let Some(pixels) = image::RgbaImage::from_raw(width, height, rgba) else { + let Ok(pixels) = + craft_image_codecs::Image::from_raw(width, height, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba) + else { self.warn(UNDECODED); return; }; - let mut png = Vec::new(); - if pixels.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).is_err() { + let Ok(png) = craft_image_codecs::encode(&pixels, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) else { self.warn(UNDECODED); return; - } + }; let href = self.blob_href(&ImageBlob::png(png)); self.colorized_hrefs.insert(key.clone(), href.clone()); href @@ -521,11 +528,18 @@ impl Writer<'_> { let (cols, rows) = (along(cover.width()), along(cover.height())); (g.pixels(b, cover, cols, rows, fill, &Color::to_rgb).flatten().collect(), cols, rows) }; - let mut png = Vec::new(); - let Some(img) = image::RgbaImage::from_raw(u32::from(cols), u32::from(rows), rgba) else { return }; - if img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).is_err() { + let Ok(img) = craft_image_codecs::Image::from_raw( + u32::from(cols), + u32::from(rows), + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + rgba, + ) else { return; - } + }; + let Ok(png) = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) else { + return; + }; self.warn(if freeform { "freeform gradients are written as images clipped to their shapes" } else if conic { diff --git a/crates/svg/src/glyph.rs b/crates/svg/src/glyph.rs index 22697f58a3..160c6679ea 100644 --- a/crates/svg/src/glyph.rs +++ b/crates/svg/src/glyph.rs @@ -2,11 +2,12 @@ //! it, made as the importer makes art of any SVG file. The text crate asks for it through the //! reader the app registers ([`vectorcraft_text::set_svg_glyph_reader`]). +use craft_svg::tree::usvg; use std::ops::Range; use std::sync::Arc; use std::sync::atomic::AtomicU64; -use usvg::roxmltree; +use craft_svg::tree::usvg::roxmltree; use vectorcraft_doc::color::Color; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; use vectorcraft_geom::Affine; diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs index 087512bf90..87e8339913 100644 --- a/crates/svg/src/import.rs +++ b/crates/svg/src/import.rs @@ -1,11 +1,12 @@ //! usvg tree → document conversion. +use craft_svg::tree::usvg; use std::borrow::Cow; use std::collections::{HashMap, HashSet}; use std::str::FromStr; use std::sync::Arc; -use usvg::roxmltree; +use craft_svg::tree::usvg::roxmltree; use vectorcraft_color::{BlendMode, Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint}; use vectorcraft_doc::{ Appearance, AppearanceItem, Dash, Document, FillLayer, ForeignAttribute, ImageBlob, ImageObject, LayerColor, LineCap, LineJoin, MAX_SVG_SCRIPTS, diff --git a/crates/svg/src/import/convert.rs b/crates/svg/src/import/convert.rs index 8bdadb0318..676708a09d 100644 --- a/crates/svg/src/import/convert.rs +++ b/crates/svg/src/import/convert.rs @@ -1,4 +1,5 @@ use super::{Affine, Arc, BezPath, BlendMode, Color, FillRule, GradientStop, HashMap, Node, PathData, Point, XNode, roxmltree}; +use craft_svg::tree::usvg; use vectorcraft_geom::path::{Anchor, AnchorKind, SubPath}; use vectorcraft_geom::shapes::KAPPA; @@ -105,7 +106,7 @@ pub(super) fn only_clips(g: &usvg::Group) -> bool { } pub(super) fn blend(b: usvg::BlendMode) -> BlendMode { - use usvg::BlendMode as B; + use craft_svg::tree::usvg::BlendMode as B; match b { B::Normal => BlendMode::Normal, B::Multiply => BlendMode::Multiply, @@ -127,7 +128,7 @@ pub(super) fn blend(b: usvg::BlendMode) -> BlendMode { } pub(super) fn bezpath(p: &usvg::tiny_skia_path::Path, m: Affine) -> BezPath { - use usvg::tiny_skia_path::PathSegment as S; + use craft_svg::tree::usvg::tiny_skia_path::PathSegment as S; let pt = |p: usvg::tiny_skia_path::Point| m * Point::new(p.x as f64, p.y as f64); let mut bp = BezPath::new(); for s in p.segments() { @@ -147,7 +148,7 @@ pub(super) fn bezpath(p: &usvg::tiny_skia_path::Path, m: Affine) -> BezPath { /// smooth anchors on the axes in the same order, each quarter a cubic with handles [`KAPPA`] of the /// radii long, the ellipse export writes as ``. `None` when `p` is not such an outline. pub(super) fn drawn_ellipse(p: &usvg::tiny_skia_path::Path) -> Option { - use usvg::tiny_skia_path::PathSegment as S; + use craft_svg::tree::usvg::tiny_skia_path::PathSegment as S; let mut ends = vec![]; let mut closed = false; for s in p.segments() { diff --git a/crates/svg/src/import/css.rs b/crates/svg/src/import/css.rs index fd864a547e..d444fc4d6b 100644 --- a/crates/svg/src/import/css.rs +++ b/crates/svg/src/import/css.rs @@ -7,11 +7,12 @@ //! skipped. Precedence: `!important`, then the `style` attribute, then specificity, then source //! order; a presentation attribute applies only when no rule sets the property. +use craft_svg::tree::usvg; use std::cell::RefCell; use std::collections::{HashMap, HashSet}; use std::rc::Rc; -use usvg::roxmltree; +use craft_svg::tree::usvg::roxmltree; pub(super) type XNode<'a, 'i> = roxmltree::Node<'a, 'i>; diff --git a/crates/svg/src/import/css_transform.rs b/crates/svg/src/import/css_transform.rs index 235d237453..da43953bb8 100644 --- a/crates/svg/src/import/css_transform.rs +++ b/crates/svg/src/import/css_transform.rs @@ -8,10 +8,11 @@ //! functions SVG lacks (`translateX`, `scaleY`, `skew`…) spelled with SVG's. A value that can't be //! (percentages, `em`, 3D functions) is left as it is. +use craft_svg::tree::usvg; use std::f64::consts::PI; use std::ops::Range; -use usvg::roxmltree; +use craft_svg::tree::usvg::roxmltree; use super::css::XNode; diff --git a/crates/svg/src/import/depth.rs b/crates/svg/src/import/depth.rs index 0586deaf6f..f3c89aafbc 100644 --- a/crates/svg/src/import/depth.rs +++ b/crates/svg/src/import/depth.rs @@ -12,11 +12,12 @@ //! the same stack: the depths of the SVGs around it are added to its own, and an image past the //! cap is left out (`files`). +use craft_svg::tree::usvg; use std::borrow::Cow; use std::collections::HashMap; use std::collections::hash_map::Entry; -use usvg::roxmltree; +use craft_svg::tree::usvg::roxmltree; use super::css::{Styles, XNode, parse_decls}; diff --git a/crates/svg/src/import/files.rs b/crates/svg/src/import/files.rs index d2b5504f9d..ea14fdd331 100644 --- a/crates/svg/src/import/files.rs +++ b/crates/svg/src/import/files.rs @@ -12,12 +12,13 @@ //! turns or flips its pixels is turned before usvg gets it, so it is sized, fitted and stored as //! it is shown. +use craft_svg::tree::usvg; use std::collections::HashMap; use std::path::Path; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; -use usvg::{ImageHrefResolver, ImageKind, roxmltree}; +use craft_svg::tree::usvg::{ImageHrefResolver, ImageKind, roxmltree}; use vectorcraft_doc::LinkInfo; use vectorcraft_doc::links::missing_placeholder; @@ -337,7 +338,7 @@ impl Files { let Some((bytes, link)) = read(file) else { return Some(Outcome::not_read("not found")) }; let counted = if nested { bytes.len() as u64 } else { 0 }; reading.svg_text = reading.svg_text.saturating_add(counted); - if nested && reading.spent() && image::guess_format(&bytes).is_ok() { + if nested && reading.spent() && craft_image_codecs::detect(&bytes).is_some() { self.too_much_linked.store(true, Ordering::Relaxed); return None; } @@ -394,7 +395,7 @@ impl Files { /// (formats usvg doesn't read are stored as PNG) or an SVG, its own links not read yet; `None` /// for anything else. fn source(&mut self, bytes: Vec, link: LinkInfo) -> Option { - let Ok(format) = image::guess_format(&bytes) else { + let Some(format) = craft_image_codecs::detect(&bytes) else { // Unpacked once, here, within what the SVGZ images may unpack to. let text = crate::text_within(&bytes, &self.unpacked).ok()?; return text.contains(" F::Jpeg, "image/png" => F::Png, @@ -503,7 +504,7 @@ impl Files { "image/webp" => F::WebP, "image/tiff" => F::Tiff, "image/svg+xml" => return self.svg_data(&bytes, opts), - "text/plain" => match image::guess_format(&bytes).ok().filter(|f| raster(*f).is_some() || *f == F::Tiff) { + "text/plain" => match craft_image_codecs::detect(&bytes).filter(|f| raster(*f).is_some() || *f == F::Tiff) { Some(format) => format, None => return self.svg_data(&bytes, opts), }, @@ -599,8 +600,8 @@ impl Files { } /// How usvg holds a raster of `format`, for the formats it reads. -fn raster(format: image::ImageFormat) -> Option { - use image::ImageFormat as F; +fn raster(format: craft_image_codecs::Format) -> Option { + use craft_image_codecs::Format as F; match format { F::Png => Some(ImageKind::PNG), F::Jpeg => Some(ImageKind::JPEG), @@ -620,8 +621,8 @@ fn raster(format: image::ImageFormat) -> Option { /// turned ([`vectorcraft_doc::cmyk::turned_cmyk`]). `None` when the pixels can't be read, and for /// a TIFF with more strips or tiles than the decoder can count /// ([`vectorcraft_doc::cmyk::oversized_tiff`]), before any decoder opens it. -fn shown(bytes: Arc>, format: image::ImageFormat) -> Option { - use image::ImageFormat as F; +fn shown(bytes: Arc>, format: craft_image_codecs::Format) -> Option { + use craft_image_codecs::Format as F; if vectorcraft_doc::cmyk::oversized_tiff(&bytes).is_some() { return None; } @@ -632,7 +633,7 @@ fn shown(bytes: Arc>, format: image::ImageFormat) -> Option { { return Some(Shown { kind, bytes, cmyk: None }); } - let tiff = image::guess_format(&bytes).ok() == Some(F::Tiff); + let tiff = craft_image_codecs::detect(&bytes) == Some(F::Tiff); let mut img = if tiff { tiff_pixels(&bytes)? } else { decoded(&bytes, format)? }; let cmyk = match orientation { Some(o) if matches!(format, F::Jpeg | F::Tiff) => vectorcraft_doc::cmyk::turned_cmyk(&bytes, o, None).map(|(tiff, _)| tiff), @@ -642,30 +643,34 @@ fn shown(bytes: Arc>, format: image::ImageFormat) -> Option { if let Some(orientation) = orientation { img.apply_orientation(orientation); } - let mut png = Vec::new(); - img.write_to(&mut std::io::Cursor::new(&mut png), F::Png).ok()?; + let rgba = img.to_rgba8(); + let raw = craft_image_codecs::Image::from_raw( + rgba.width(), + rgba.height(), + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + rgba.into_raw(), + ) + .ok()?; + let png = craft_image_codecs::encode(&raw, F::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; Some(Shown { kind: ImageKind::PNG, bytes: Arc::new(png), cmyk }) } /// The pixels of encoded image `bytes` (`format` when their bytes don't say), as stored, decoded /// within [`vectorcraft_doc::MAX_RASTER_ALLOC`], counted as decoded and as RGBA, as Open and Place /// decode them; `None` when they can't be. -fn decoded(bytes: &[u8], format: image::ImageFormat) -> Option { - use image::ImageDecoder as _; +fn decoded(bytes: &[u8], format: craft_image_codecs::Format) -> Option { let max = vectorcraft_doc::MAX_RASTER_ALLOC; - let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?; - if reader.format().is_none() { - reader.set_format(format); - } - let mut limits = image::Limits::default(); - limits.max_alloc = Some(max); - reader.limits(limits); - let decoder = reader.into_decoder().ok()?; - let (w, h) = decoder.dimensions(); - if decoder.total_bytes() > max || u64::from(w) * u64::from(h) * 4 > max { + let detected = craft_image_codecs::detect(bytes).unwrap_or(format); + let mut opts = craft_image_codecs::DecodeOptions::default(); + opts.limits.max_alloc = max; + opts.keep_orientation = true; + let img = craft_image_codecs::decode_as_with(detected, bytes, &opts).ok()?; + let (w, h) = img.dimensions(); + if u64::from(w) * u64::from(h) * 4 > max { return None; } - image::DynamicImage::from_decoder(decoder).ok() + image::RgbaImage::from_raw(w, h, img.to_rgba8()).map(image::DynamicImage::ImageRgba8) } /// The pixels of TIFF `bytes`, as stored, read as Open and Place read them: a TIFF with extra @@ -683,7 +688,8 @@ fn tiff_pixels(bytes: &[u8]) -> Option { if let Some(read) = vectorcraft_doc::cmyk::group3_tiff_rgba(bytes) { return read.ok().map(ImageRgba8); } - decoded(bytes, image::ImageFormat::Tiff).or_else(|| decoded(&vectorcraft_doc::cmyk::stored_cmyk_tiff(bytes, None)?, image::ImageFormat::Tiff)) + decoded(bytes, craft_image_codecs::Format::Tiff) + .or_else(|| decoded(&vectorcraft_doc::cmyk::stored_cmyk_tiff(bytes, None)?, craft_image_codecs::Format::Tiff)) } /// No image: left out, noted in `why` when `noted`. @@ -893,9 +899,9 @@ mod tests { } fn png() -> Vec { - let mut out = vec![]; - image::RgbaImage::new(1, 1).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); - out + let img = craft_image_codecs::Image::from_raw(1, 1, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, vec![0; 4]) + .unwrap(); + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap() } fn linked_note() -> String { diff --git a/crates/svg/src/import/fx.rs b/crates/svg/src/import/fx.rs index b760b1b119..c114d7e624 100644 --- a/crates/svg/src/import/fx.rs +++ b/crates/svg/src/import/fx.rs @@ -7,12 +7,15 @@ //! blurred with a fixed amount subtracted from its colors by `feComponentTransfer` (Darkness), and what //! our export writes, so export → import keeps the effects. +use craft_svg::tree::usvg; use std::collections::HashMap; use std::sync::Arc; +use craft_svg::tree::usvg::filter::{ + ColorInterpolation, ColorMatrixKind, CompositeOperator, Filter, Input, Kind, MorphologyOperator, TransferFunction, +}; +use craft_svg::tree::usvg::roxmltree; use serde_json::json; -use usvg::filter::{ColorInterpolation, ColorMatrixKind, CompositeOperator, Filter, Input, Kind, MorphologyOperator, TransferFunction}; -use usvg::roxmltree; use vectorcraft_color::Color; use vectorcraft_doc::Effect; use vectorcraft_geom::{Affine, Vec2}; diff --git a/crates/svg/src/import/importer.rs b/crates/svg/src/import/importer.rs index 2eede1f7be..683c5dd867 100644 --- a/crates/svg/src/import/importer.rs +++ b/crates/svg/src/import/importer.rs @@ -7,6 +7,7 @@ use super::{ StrokeLayer, Vec2, fnv1a, fx, shapes, text, vector_effect, }; use crate::SvgError; +use craft_svg::tree::usvg; use kurbo::BezPath; use vectorcraft_color::GradientSpread; @@ -766,10 +767,9 @@ impl Importer { usvg::ImageKind::SVG(tree) => return self.svg_image(tree, acc), }; let size = i.size(); - let (pw, ph) = image::ImageReader::new(std::io::Cursor::new(&bytes[..])) - .with_guessed_format() + let (pw, ph) = craft_image_codecs::probe_size(bytes) .ok() - .and_then(|r| r.into_dimensions().ok()) + .or_else(|| craft_image_codecs::decode(bytes).ok().map(|i| i.dimensions())) .unwrap_or((size.width().round().max(1.0) as u32, size.height().round().max(1.0) as u32)); // A turned CMYK image is stored as the CMYK TIFF of its inks, the size of the PNG usvg got. let cmyk = self.files.stored(i.kind()); diff --git a/crates/svg/src/import/layers.rs b/crates/svg/src/import/layers.rs index a6d6a46b30..20082bdeea 100644 --- a/crates/svg/src/import/layers.rs +++ b/crates/svg/src/import/layers.rs @@ -1,6 +1,7 @@ use super::convert::made_up; use super::importer::{CSS_PX_PER_IN, PT_PER_IN}; use super::{Affine, Arc, FromStr, HashSet, Node, NodeId, NodeKind, Rect, Unit, XNode, roxmltree}; +use craft_svg::tree::usvg; /// What marks a nested `` as a sublayer rather than a group: our export writes it on the layers /// it writes inside layers. (Inkscape's `inkscape:groupmode="layer"` counts too.) @@ -94,7 +95,7 @@ impl RootUnits { /// `'id' (feA, feB)` for each filter: its id and the primitives it uses, for warnings. pub(super) fn filter_names(filters: &[Arc]) -> String { - use usvg::filter::Kind as K; + use craft_svg::tree::usvg::filter::Kind as K; let names: Vec = filters .iter() .map(|f| { diff --git a/crates/svg/src/import/linear_rgb.rs b/crates/svg/src/import/linear_rgb.rs index 8286e0a94b..5ed17a3f46 100644 --- a/crates/svg/src/import/linear_rgb.rs +++ b/crates/svg/src/import/linear_rgb.rs @@ -3,6 +3,7 @@ //! linear light, which a document gradient (mixed in display RGB) shows through extra stops. use super::{Color, GradientStop, HashMap, HashSet, css, roxmltree}; +use craft_svg::tree::usvg; use vectorcraft_color::cms::lab::{linear_to_srgb, srgb_to_linear}; /// How far (display RGB, 0..1) the straight line between neighbouring baked stops may stray from diff --git a/crates/svg/src/import/symbol_units.rs b/crates/svg/src/import/symbol_units.rs index b038b20ff3..792453a0a3 100644 --- a/crates/svg/src/import/symbol_units.rs +++ b/crates/svg/src/import/symbol_units.rs @@ -6,10 +6,11 @@ //! the `viewBox`, so it comes out too large and out of place (#1561). Before usvg runs, the //! percentages of the shapes' geometry are rewritten in the `viewBox`'s units. +use craft_svg::tree::usvg; use std::ops::Range; use std::str::FromStr; -use usvg::roxmltree; +use craft_svg::tree::usvg::roxmltree; /// The elements whose geometry attributes are rewritten. const SHAPES: &[&str] = &["rect", "circle", "ellipse", "line", "image", "use", "text"]; diff --git a/crates/svg/src/import/text.rs b/crates/svg/src/import/text.rs index cbffbfc348..4268b229bf 100644 --- a/crates/svg/src/import/text.rs +++ b/crates/svg/src/import/text.rs @@ -27,6 +27,7 @@ //! moves into its sizes ([`size_scale`], [`fold_scale`]), and the rest (a stretch, skew, //! rotation or reflection) stays its transform. +use craft_svg::tree::usvg; use std::borrow::Cow; use std::cell::RefCell; use std::collections::HashMap; @@ -35,7 +36,7 @@ use std::ops::{Range, RangeInclusive}; use std::rc::Rc; use std::str::FromStr; -use usvg::roxmltree; +use craft_svg::tree::usvg::roxmltree; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{CharStyle, Dash, Justify, LineCap, LineJoin, ParaDirection, ParaStyle, StrokeLayer, TextKind, TextObject, TextRun}; use vectorcraft_geom::kurbo::ParamCurveArclen; diff --git a/crates/svg/src/import/vector_effect.rs b/crates/svg/src/import/vector_effect.rs index 4a80a2fa08..974f113211 100644 --- a/crates/svg/src/import/vector_effect.rs +++ b/crates/svg/src/import/vector_effect.rs @@ -4,9 +4,10 @@ //! document-space stroke of the screen width is exact; type and the art usvg drops ids from //! (patterns, markers, `` copies) can't always keep it, and a warning says so. +use craft_svg::tree::usvg; use std::collections::HashSet; -use usvg::roxmltree; +use craft_svg::tree::usvg::roxmltree; use vectorcraft_doc::TextObject; use vectorcraft_geom::Affine; diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index b035e6cd10..6d66d06e39 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -101,6 +101,7 @@ //! rotation and style names). #![forbid(unsafe_code)] +use craft_svg::tree::usvg; mod css; mod entities; mod export; diff --git a/crates/svg/tests/classes.rs b/crates/svg/tests/classes.rs index b3ae4622e4..f302a06885 100644 --- a/crates/svg/tests/classes.rs +++ b/crates/svg/tests/classes.rs @@ -1,6 +1,7 @@ //! CSS classes on imported elements come back on export, beside the generated `cls-N` classes. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -use usvg::roxmltree; +use craft_svg::tree::usvg; +use craft_svg::tree::usvg::roxmltree; use vectorcraft_svg::{ExportOptions, Profile, Styling, export, import}; const SRC: &str = r#""#; diff --git a/crates/svg/tests/it/basic_shapes.rs b/crates/svg/tests/it/basic_shapes.rs index 25d13cb31c..d71a57b68b 100644 --- a/crates/svg/tests/it/basic_shapes.rs +++ b/crates/svg/tests/it/basic_shapes.rs @@ -3,6 +3,8 @@ //! rectangles and ellipses whose dashes would start elsewhere, stays ``; the picture and the //! reimported geometry don't change. +use craft_svg::tree::draw::resvg; +use craft_svg::tree::usvg; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, Dash, Document, FillLayer, Node, StrokeLayer}; use vectorcraft_geom::{Affine, PathData, Point, Rect, SubPath, shapes}; diff --git a/crates/svg/tests/it/blend_export.rs b/crates/svg/tests/it/blend_export.rs index ec947041b0..425173cfd6 100644 --- a/crates/svg/tests/it/blend_export.rs +++ b/crates/svg/tests/it/blend_export.rs @@ -1,7 +1,9 @@ //! Blend modes and opacity masks in SVG export look as on the canvas: every mode follows the //! reference formulas when resvg draws the file, and masks take luminance the canvas's way. -use usvg::roxmltree; +use craft_svg::tree::draw::resvg; +use craft_svg::tree::usvg; +use craft_svg::tree::usvg::roxmltree; use vectorcraft_color::blend::blend_rgb; use vectorcraft_color::{BlendMode, Color, Paint}; use vectorcraft_doc::{Appearance, CharStyle, Document, Node, NodeKind, OpacityMask, TextObject}; diff --git a/crates/svg/tests/it/colorized_images.rs b/crates/svg/tests/it/colorized_images.rs index d3590977f2..e1bb8d9696 100644 --- a/crates/svg/tests/it/colorized_images.rs +++ b/crates/svg/tests/it/colorized_images.rs @@ -1,5 +1,7 @@ //! Colorized gray and bilevel image export, checked as pixels as well as markup. +use craft_svg::tree::draw::resvg; +use craft_svg::tree::usvg; use vectorcraft_color::{Color, Paint, Swatch}; use vectorcraft_doc::{Document, ImageBlob, ImageObject, LinkInfo, Node, NodeKind}; use vectorcraft_geom::Affine; @@ -23,9 +25,16 @@ fn bilevel() -> Vec { } fn png(img: image::DynamicImage) -> Vec { - let mut out = Vec::new(); - img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); - out + let rgba = img.to_rgba8(); + let raw = craft_image_codecs::Image::from_raw( + rgba.width(), + rgba.height(), + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + rgba.into_raw(), + ) + .unwrap(); + craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap() } fn document(bytes: Vec, paint: Option) -> Document { @@ -131,7 +140,8 @@ fn bilevel_process_and_spot_use_coverage_in_embed_link_and_tiny() { assert_eq!(linked.linked.len(), 1); let file = &linked.linked[0]; assert!(linked.svg.contains(&file.name)); - let rgba = image::load_from_memory(&file.bytes).unwrap().to_rgba8(); + let decoded = craft_image_codecs::decode(&file.bytes).unwrap(); + let rgba = image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8()).unwrap(); assert_eq!((rgba.get_pixel(0, 0).0[3], rgba.get_pixel(1, 0).0[3]), (255, 0)); let inlined = linked.svg.replace(&file.name, &format!("data:image/png;base64,{}", base64_encode(&file.bytes))); assert_eq!(rendered(&inlined), rendered(&embedded.svg)); diff --git a/crates/svg/tests/it/dash_align.rs b/crates/svg/tests/it/dash_align.rs index 2885d37446..c24ece700d 100644 --- a/crates/svg/tests/it/dash_align.rs +++ b/crates/svg/tests/it/dash_align.rs @@ -1,6 +1,8 @@ //! Dashes fitted to corners export as the canvas's filled outlines (a dash array can't fit them); //! exact dashes stay a `stroke-dasharray`. Checked by rendering the exported SVG with resvg. +use craft_svg::tree::draw::resvg; +use craft_svg::tree::usvg; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, Dash, Document, Node, StrokeLayer}; use vectorcraft_geom::{Rect, shapes}; diff --git a/crates/svg/tests/it/data_attributes.rs b/crates/svg/tests/it/data_attributes.rs index f8151ed7da..83bcaf3be6 100644 --- a/crates/svg/tests/it/data_attributes.rs +++ b/crates/svg/tests/it/data_attributes.rs @@ -1,7 +1,8 @@ //! Synthetic XML 1.0/SVG round trips: https://www.w3.org/TR/xml/#AVNormalize //! https://www.w3.org/TR/xml/#NT-NameChar https://www.w3.org/TR/xml/#charsets +use craft_svg::tree::usvg; +use craft_svg::tree::usvg::roxmltree; use std::collections::HashSet; -use usvg::roxmltree; use vectorcraft_doc::{Document, Node}; use vectorcraft_svg::{Encoding, ExportOptions, ObjectIds, Output, Styling, export, export_full, import}; diff --git a/crates/svg/tests/it/encoding_profile_fonts.rs b/crates/svg/tests/it/encoding_profile_fonts.rs index 5468953aa4..eb0176ff10 100644 --- a/crates/svg/tests/it/encoding_profile_fonts.rs +++ b/crates/svg/tests/it/encoding_profile_fonts.rs @@ -2,6 +2,7 @@ //! back, entity styling parses in usvg, SVG Tiny 1.2 has no filters, masks, symbols or style //! sheets, and embedded fonts hold only the glyphs used where their licence allows it. +use craft_svg::tree::usvg; use std::sync::Arc; use serde_json::json; diff --git a/crates/svg/tests/it/foreign_attributes.rs b/crates/svg/tests/it/foreign_attributes.rs index da949e09a2..5aaabf894e 100644 --- a/crates/svg/tests/it/foreign_attributes.rs +++ b/crates/svg/tests/it/foreign_attributes.rs @@ -1,7 +1,8 @@ //! Attributes in other applications' XML namespaces (https://www.w3.org/TR/xml-names/) survive a //! round trip through VectorCraft: kept on import, written back on export with their namespaces //! declared on the root. -use usvg::roxmltree; +use craft_svg::tree::usvg; +use craft_svg::tree::usvg::roxmltree; use vectorcraft_doc::{Document, ForeignAttribute, Node, NodeKind}; use vectorcraft_svg::{ExportOptions, MAX_FOREIGN, MAX_FOREIGN_VALUE, export, export_full, import, import_with_report}; diff --git a/crates/svg/tests/it/image_orientation.rs b/crates/svg/tests/it/image_orientation.rs index 549a40a3bf..557903ef0c 100644 --- a/crates/svg/tests/it/image_orientation.rs +++ b/crates/svg/tests/it/image_orientation.rs @@ -49,9 +49,14 @@ fn folder(name: &str) -> PathBuf { /// A 16 × 8 JPEG, red on the left half, with an EXIF segment giving Orientation `orientation` /// when there is one. fn jpeg(orientation: Option) -> Vec { - let rgb = image::RgbImage::from_fn(16, 8, |x, _| if x < 8 { image::Rgb([220, 0, 0]) } else { image::Rgb([255, 255, 255]) }); - let mut jpg = Vec::new(); - image::DynamicImage::ImageRgb8(rgb).write_to(&mut std::io::Cursor::new(&mut jpg), image::ImageFormat::Jpeg).unwrap(); + let mut rgb = Vec::with_capacity(16 * 8 * 3); + for _ in 0..8 { + for x in 0..16 { + rgb.extend_from_slice(&if x < 8 { [220, 0, 0] } else { [255, 255, 255] }); + } + } + let raw = craft_image_codecs::Image::from_raw(16, 8, craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, rgb).unwrap(); + let jpg = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Jpeg, &craft_image_codecs::EncodeOptions::default()).unwrap(); let Some(orientation) = orientation else { return jpg }; let o = orientation.to_le_bytes(); let exif: Vec = @@ -136,7 +141,9 @@ fn near(a: Rect, b: Rect) -> bool { /// The stored pixels of `im`, as RGB. fn pixels(d: &Document, im: &ImageObject) -> image::RgbImage { - image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgb8() + let decoded = craft_image_codecs::decode(&d.images[&im.key].bytes).unwrap(); + let rgba = image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8()).unwrap(); + image::DynamicImage::ImageRgba8(rgba).into_rgb8() } fn red(p: &image::Rgb) -> bool { @@ -200,7 +207,9 @@ fn a_turned_tiff_imports_upright() { let what = &href[..href.len().min(20)]; assert_eq!((im.width, im.height), (2, 4), "{what}: turned a quarter"); assert!(near(placed(&im), Rect::new(0.0, 0.0, 20.0, 40.0)), "{what}: {:?}", placed(&im)); - let px = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_luma8(); + let decoded = craft_image_codecs::decode(&d.images[&im.key].bytes).unwrap(); + let px = + image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8()).unwrap()).into_luma8(); assert_eq!((px.get_pixel(0, 0)[0], px.get_pixel(1, 1)[0], px.get_pixel(0, 3)[0]), (0, 0, 255), "{what}: the left half is on top"); } } @@ -235,7 +244,8 @@ fn a_gray_tiff_with_alpha_imports_turned_or_not() { let href = format!("data:image/tiff;base64,{}", base64_encode(&tiff(4, 2, 2, &data, orientation))); let (d, im) = import_one(&format!(r#""#), None); assert_eq!((im.width, im.height), size, "orientation {orientation}"); - let px = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8(); + let decoded = craft_image_codecs::decode(&d.images[&im.key].bytes).unwrap(); + let px = image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8()).unwrap(); assert_eq!(px.get_pixel(black_at.0, black_at.1).0, [0, 0, 0, 255], "orientation {orientation}: black"); assert_eq!(px.get_pixel(clear_at.0, clear_at.1)[3], 0, "orientation {orientation}: clear"); } diff --git a/crates/svg/tests/it/import_details.rs b/crates/svg/tests/it/import_details.rs index 69e5cafa21..b81ccebdae 100644 --- a/crates/svg/tests/it/import_details.rs +++ b/crates/svg/tests/it/import_details.rs @@ -2,6 +2,8 @@ //! and a warning when missing), SVG images as vector art, nested clips, undisplayed objects as //! hidden objects, and reflected or repeated gradients. +use craft_svg::tree::draw::resvg; +use craft_svg::tree::usvg; use std::path::{Path, PathBuf}; use vectorcraft_doc::{Document, ImageObject, LinkInfo, Node, NodeKind}; @@ -44,11 +46,15 @@ fn resvg_render(svg: &str, w: u32, h: u32) -> Image { } fn png(w: u32, h: u32) -> Vec { - let mut out = vec![]; - image::RgbaImage::from_pixel(w, h, image::Rgba([10, 200, 30, 255])) - .write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png) - .unwrap(); - out + let img = craft_image_codecs::Image::from_raw( + w, + h, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + [10u8, 200, 30, 255].repeat((w * h) as usize), + ) + .unwrap(); + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap() } /// A fresh folder for one test's files. diff --git a/crates/svg/tests/it/import_live.rs b/crates/svg/tests/it/import_live.rs index 1d10c5d9fe..508facbb9c 100644 --- a/crates/svg/tests/it/import_live.rs +++ b/crates/svg/tests/it/import_live.rs @@ -2,6 +2,8 @@ //! with `` a symbol and its instances, blurs and drop-shadow chains live effects; and //! export → import keeps them. +use craft_svg::tree::draw::resvg; +use craft_svg::tree::usvg; use std::sync::Arc; use serde_json::json; diff --git a/crates/svg/tests/it/interactivity.rs b/crates/svg/tests/it/interactivity.rs index 66b98959b1..0e3d4de3b1 100644 --- a/crates/svg/tests/it/interactivity.rs +++ b/crates/svg/tests/it/interactivity.rs @@ -2,10 +2,11 @@ //! and `