mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-21 18:04:03 +01:00
chore(codecs): cut over remaining image/tiff/ccitt codecs to craft-libs
This commit is contained in:
1 parent
bada8e1710
commit
1d6c4dcd14
279 files changed
+12516
-3487
No files matched your search
+10
-30
@@ -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 `<text>` 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"
|
||||
|
||||
@@ -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 }
|
||||
@@ -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]));
|
||||
}
|
||||
|
||||
@@ -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 }
|
||||
|
||||
+21
-18
@@ -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))
|
||||
}
|
||||
}
|
||||
|
||||
+24
-4
@@ -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(),
|
||||
|
||||
@@ -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 }
|
||||
+376
-355
@@ -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<usize> {
|
||||
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<Cursor<&[u8]>>)> {
|
||||
/// Parsed TIFF `bytes`; `None` for non-TIFF or [`oversized_tiff`] images.
|
||||
pub(crate) fn parse_tiff(bytes: &[u8]) -> Option<craft_tiff::Tiff> {
|
||||
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<craft_tiff::image::ImageInfo> {
|
||||
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<u16> {
|
||||
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<u16> {
|
||||
let (_, mut d) = tiff(bytes)?;
|
||||
d.find_tag_unsigned::<u16>(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<u16> {
|
||||
/// 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<image::metadata::Orientation> {
|
||||
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<Cursor<&[u8]>>) -> bool {
|
||||
d.find_tag_unsigned::<u16>(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<Cursor<&[u8]>>, n: usize, per: usize) -> Option<Vec<u8>> {
|
||||
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<Cursor<&[u8]>>, n: usize, per: usize) -> Option<Samples> {
|
||||
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<Samples> {
|
||||
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<T: Copy>(data: Vec<T>, planes: usize, n: usize, per: usize) -> Option<Vec<T>> {
|
||||
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<Cursor<&[u8]>>) -> Option<Vec<u8>> {
|
||||
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<Vec<u8>> {
|
||||
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<Vec<u8>> {
|
||||
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<Vec<u8>> {
|
||||
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<CmykSource> {
|
||||
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<CmykSource> {
|
||||
/// 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<Vec<u8>> {
|
||||
use tiff::encoder::colortype::{CMYK8, CMYK16, ColorType};
|
||||
use tiff::encoder::{Compression, ImageEncoder, Rational, TiffEncoder, TiffKind, compression::DeflateLevel};
|
||||
use tiff::tags::{ResolutionUnit, Tag};
|
||||
fn tags<W: std::io::Write + std::io::Seek, C: ColorType, K: TiffKind>(
|
||||
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::<CMYK8>(width, height).ok()?;
|
||||
tags(&mut img, ppi, icc)?;
|
||||
img.write_data(data).ok()?;
|
||||
}
|
||||
SampleSlice::Sixteen(data) => {
|
||||
let mut img = enc.new_image::<CMYK16>(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<u8>) = 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<Inks> {
|
||||
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<Inks> {
|
||||
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<Inks> {
|
||||
/// whose inks [`ImageBlob::cmyk`] doesn't read.
|
||||
pub fn stored_cmyk_tiff(bytes: &[u8], ppi: Option<(f64, f64)>) -> Option<Vec<u8>> {
|
||||
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<image::RgbaImage> {
|
||||
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::<u16>(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::<u16>(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<Result<image::RgbaImage, Group3Error>> {
|
||||
use hayro_ccitt::{DecodeError, DecodeSettings, DecoderContext, EncodingMode};
|
||||
use tiff::tags::Tag;
|
||||
let (kind, mut d) = tiff(bytes)?;
|
||||
let compression = d.find_tag_unsigned::<u16>(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::<u16>(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::<u32>(Tag::Unknown(292)).ok().flatten().unwrap_or(0);
|
||||
let lsb_first = d.find_tag_unsigned::<u16>(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::<u32>(Tag::TileWidth).ok().flatten().filter(|&v| v > 0)?;
|
||||
let th = d.find_tag_unsigned::<u32>(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::<u32>(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::<u64>(offsets).ok().flatten().unwrap_or_default();
|
||||
let counts = d.find_tag_unsigned_vec::<u64>(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<u8> {
|
||||
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<u8> {
|
||||
use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value, tags};
|
||||
let raw: Vec<u8> = 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::<CMYKA8>(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<u8>) {
|
||||
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::<GrayExtra8>(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<u16>) {
|
||||
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<u16>) {
|
||||
result.extend_from_slice(row);
|
||||
}
|
||||
}
|
||||
|
||||
/// A one-row TIFF of `C`'s pixels `data`, with the ExtraSamples value `extra`.
|
||||
fn extra_tiff<C: tiff::encoder::colortype::ColorType<Inner = u16>>(extra: u16, data: &[u16]) -> Vec<u8> {
|
||||
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::<C>(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::<Cmyka16>(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::<GrayExtra16>(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::<CMYKA8>(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::<GrayExtra16>(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<u8> = (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);
|
||||
}
|
||||
|
||||
+217
-36
@@ -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<image::DynamicImage>)> {
|
||||
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<Vec<u8>> {
|
||||
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<image::DynamicImage, bool> {
|
||||
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<Vec<u8>> {
|
||||
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<Vec<u8>> {
|
||||
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<Vec<u8>> {
|
||||
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<u8> {
|
||||
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));
|
||||
}
|
||||
|
||||
+215
-34
@@ -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<image::RgbaImage> {
|
||||
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<GraySource> {
|
||||
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]));
|
||||
|
||||
@@ -347,7 +347,7 @@ pub fn full_bytes(p: &PlacedDocument, blob: &ImageBlob) -> Option<Arc<Vec<u8>>>
|
||||
|
||||
/// 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);
|
||||
|
||||
+134
-67
@@ -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<ImageBlob> {
|
||||
let gray: Vec<u8> = 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<Self> {
|
||||
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::<colortype::CMYK8>(s.width, s.height).ok()?;
|
||||
let deflate = |raw: &[u8]| -> Option<Vec<u8>> {
|
||||
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<String> =
|
||||
[(!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::<colortype::Gray8>(s.width, s.height).ok()?;
|
||||
img.encoder().write_tag(Tag::ImageDescription, description(p).as_str()).ok()?;
|
||||
let inverted: Vec<u8> = 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<PlateFile> {
|
||||
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<PathData> {
|
||||
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<Separated> {
|
||||
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<String>) -> 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::<colortype::CMYK8>(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::<colortype::Gray8>(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::<colortype::CMYK8>(1, 1, &[0, 0, 0, 0]).unwrap();
|
||||
let mut img = enc.new_image::<colortype::Gray8>(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::<colortype::Gray8>(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());
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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<String> {
|
||||
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<Self> {
|
||||
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
|
||||
|
||||
@@ -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<Vec<u8>>) -> 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(…)`.
|
||||
|
||||
@@ -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<u8> {
|
||||
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<u8> {
|
||||
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]);
|
||||
|
||||
@@ -15,10 +15,13 @@ fn fx(id: &str) -> Effect {
|
||||
}
|
||||
|
||||
/// `img` encoded as `format`.
|
||||
fn encoded(img: image::DynamicImage, format: image::ImageFormat) -> Vec<u8> {
|
||||
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<u8> {
|
||||
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<Rect> {
|
||||
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));
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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<Value> {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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<Pixels>, bool, Option<Vec<u8>>)> {
|
||||
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
|
||||
|
||||
@@ -287,9 +287,7 @@ fn apply_color_mask(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// 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
|
||||
|
||||
@@ -15,7 +15,41 @@ const RED: [u8; 4] = [200, 0, 0, 255];
|
||||
|
||||
fn png(img: DynamicImage) -> Vec<u8> {
|
||||
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));
|
||||
}
|
||||
@@ -21,7 +21,41 @@ fn settings(background: Background) -> Settings {
|
||||
|
||||
fn png(img: DynamicImage) -> Vec<u8> {
|
||||
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<Vec<u8>> {
|
||||
}
|
||||
|
||||
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<u8> = 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
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -526,26 +526,34 @@ fn doc_compare(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// 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<image::RgbaImage> {
|
||||
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")]
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<u8>) -> Option<Vec<u8>> {
|
||||
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`).
|
||||
|
||||
@@ -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<T>(_bytes: &[u8], _read: impl FnOnce(&[u8]) -> Option<T>
|
||||
|
||||
#[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<image::RgbaImage, String> {
|
||||
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<T>(bytes: &[u8], read: impl FnOnce(&[u8]) -> Option<T>) -> Option<T> {
|
||||
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<image::RgbaImage, String> {
|
||||
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<impl Iterator<Item = u32>> {
|
||||
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<bool> {
|
||||
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<u64> {
|
||||
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<u64> {
|
||||
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<Nclx> {
|
||||
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<Nclx> {
|
||||
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<heic_rs::Image> {
|
||||
use heic_rs::hevc::Frame;
|
||||
|
||||
fn coded(ctx: &Context<'_>, id: u32) -> heic_rs::Result<Frame> {
|
||||
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<Frame> {
|
||||
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::<heic_rs::Result<Vec<_>>>()?
|
||||
};
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let frames = tiles.iter().map(|&t| coded(ctx, t)).collect::<heic_rs::Result<Vec<_>>>()?;
|
||||
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<u64> {
|
||||
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<u64> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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<Vec<u8>> {
|
||||
(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<Nclx> {
|
||||
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<u64> = 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<u64> {
|
||||
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<u64> {
|
||||
(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<u64> {
|
||||
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<vectorcraft_color::cms::IccProfile> {
|
||||
fn source_profile(icc: Option<&[u8]>, colour: Colour) -> Option<vectorcraft_color::cms::IccProfile> {
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -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<Item = (&[u8], &[u8])> {
|
||||
})
|
||||
}
|
||||
|
||||
/// 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<usize>| 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<u64> {
|
||||
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<Option<u64>, ()> {
|
||||
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<image::RgbaImage, String> {
|
||||
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())
|
||||
}
|
||||
@@ -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<Vec<u8>>, 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<f32>; 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<Option<Vec<u8>>
|
||||
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<Option<Vec<u8>>, 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<dyn std::error::Error + Send + Sync>, 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::<jxl_grid::OutOfMemory>());
|
||||
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")
|
||||
}
|
||||
|
||||
@@ -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<String> {
|
||||
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<String> {
|
||||
pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
|
||||
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<RasterImage> {
|
||||
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<RasterImage> {
|
||||
_ => 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<RasterImage> {
|
||||
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<image::DynamicImage>, icc: Option<Vec<u8>>, ppi: Option<(f64, f64)>) -> Result<RasterImage> {
|
||||
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<u16>| v.into_iter().flat_map(u16::to_ne_bytes).collect::<Vec<u8>>();
|
||||
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<String> {
|
||||
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"))
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -257,7 +257,41 @@ mod tests {
|
||||
|
||||
fn png_of(w: u32, h: u32) -> Vec<u8> {
|
||||
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)));
|
||||
|
||||
@@ -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<u8> {
|
||||
fn image_bytes(w: u32, h: u32, format: craft_image_codecs::Format) -> Vec<u8> {
|
||||
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<u8>>, Vec<u8>) {
|
||||
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<u8> = (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<u8> = 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"<?xml version=\"1.0\"?><svg xmlns=\"http://www.w3.org/2000/svg\"/>").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<u8> =
|
||||
[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<u8>| 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<u16> { 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<u8> {
|
||||
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<Vec<u8>>, image::ExtendedColorType, image::DynamicImage) {
|
||||
use image::ImageDecoder as _;
|
||||
let bytes = Cursor::new(img.blob.bytes.as_slice());
|
||||
let mut d: Box<dyn image::ImageDecoder> = 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<Vec<u8>>, 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<Vec<u8>>, 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<u16>| {
|
||||
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}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,41 @@ use std::io::Cursor;
|
||||
fn png() -> Vec<u8> {
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
@@ -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::<Vec<_>>());
|
||||
});
|
||||
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");
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -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}");
|
||||
|
||||
@@ -16,7 +16,24 @@ fn b64(v: &Value) -> Vec<u8> {
|
||||
}
|
||||
|
||||
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 {
|
||||
|
||||
@@ -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<bool>, 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<bool>, 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<bool> {
|
||||
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<bool> {
|
||||
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<bool>) -> Vec<u8> {
|
||||
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<bool>) -> Vec<u8> {
|
||||
put(&mut bits, 1, 1);
|
||||
while !bits.len().is_multiple_of(8) {
|
||||
bits.push(false);
|
||||
}
|
||||
let rbsp: Vec<u8> = 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<u8> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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() {
|
||||
|
||||
@@ -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<u8> {
|
||||
@@ -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::<Vec<_>>(), 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::<Vec<_>>(),
|
||||
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::<Vec<_>>(), 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::<Vec<_>>(),
|
||||
COLORS
|
||||
);
|
||||
assert!(load::texture_image(bytes).is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<u8> {
|
||||
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<u8> {
|
||||
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<u16> = 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<u8> {
|
||||
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<u8> {
|
||||
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<u8> = 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::<Vec<_>>(), want);
|
||||
// Gray, 16 bits, in the container, opened as a document.
|
||||
let gray: Vec<u8> = [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<u8> = (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::<Vec<_>>(), 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)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
);
|
||||
}
|
||||
@@ -49,7 +49,27 @@ fn rle(raw: &[u8]) -> Vec<u8> {
|
||||
/// 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).
|
||||
|
||||
@@ -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 [
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -807,7 +807,28 @@ fn image_outline(doc: &vectorcraft_doc::Document) -> Vec<String> {
|
||||
((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");
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -213,7 +213,24 @@ fn exported(s: &mut Session, p: Value) -> Vec<u8> {
|
||||
#[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();
|
||||
|
||||
@@ -72,7 +72,27 @@ fn wide(samples: &[u16]) -> Vec<u8> {
|
||||
/// 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::<Vec<_>>(), 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);
|
||||
|
||||
@@ -16,7 +16,24 @@ fn b64(v: &Value) -> Vec<u8> {
|
||||
}
|
||||
|
||||
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.
|
||||
|
||||
@@ -34,7 +34,25 @@ fn names(r: &Value) -> Vec<String> {
|
||||
}
|
||||
|
||||
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"}]}),
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
@@ -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}");
|
||||
|
||||
@@ -32,9 +32,41 @@ impl Drop for Folder {
|
||||
|
||||
fn png(w: u32, h: u32) -> Vec<u8> {
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
|
||||
@@ -71,7 +71,8 @@ fn carry(from: &Node, mut to: Node) -> Node {
|
||||
/// everywhere).
|
||||
pub(crate) fn see_through_images(doc: &Document) -> BTreeSet<String> {
|
||||
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()
|
||||
}
|
||||
|
||||
@@ -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<Vec<u8>, 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<u8> = 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<Value> {
|
||||
|
||||
@@ -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<Value> {
|
||||
/// The image's pixels as RGBA, held to the allowance opening a raster has.
|
||||
fn decode_rgba(c: &str, blob: &vectorcraft_doc::ImageBlob) -> Result<image::RgbaImage> {
|
||||
// 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<Value> {
|
||||
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 }))
|
||||
}
|
||||
|
||||
@@ -888,15 +888,9 @@ fn queue(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// 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",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -295,17 +295,31 @@ fn preview(doc: &Document, art: &Node, frame: Rect) -> Option<Vec<u8>> {
|
||||
})
|
||||
.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).
|
||||
|
||||
@@ -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) };
|
||||
|
||||
@@ -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<u8>, 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.
|
||||
|
||||
@@ -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]);
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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"<svg xmlns=\"http://www.w3.org/2000/svg\"><rect width=\"4\" height=\"4\"/></svg>";
|
||||
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<u8> {
|
||||
})
|
||||
.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
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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<u8> {
|
||||
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"]);
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -403,14 +403,68 @@ fn blend_moves_a_mesh_to_the_blended_colour() {
|
||||
fn png(px: [[u8; 4]; 4]) -> Vec<u8> {
|
||||
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();
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<f64> = 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<f64> = 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();
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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<u8> {
|
||||
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<u8> {
|
||||
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<u8>) {
|
||||
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<u8> {
|
||||
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))));
|
||||
|
||||
@@ -35,7 +35,41 @@ impl Drop for Folder {
|
||||
pub(crate) fn png(w: u32, h: u32, rgb: [u8; 3]) -> Vec<u8> {
|
||||
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<u8> {
|
||||
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));
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -38,7 +38,41 @@ fn with(mut n: Node, fx: Effect) -> Node {
|
||||
fn png(w: u32, h: u32) -> Vec<u8> {
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
@@ -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<f64>) -> Vec<u8> {
|
||||
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<u8> {
|
||||
fn noise(w: u32, h: u32, format: craft_image_codecs::Format) -> Vec<u8> {
|
||||
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<u8> {
|
||||
/// 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();
|
||||
|
||||
@@ -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 =
|
||||
|
||||
@@ -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"}));
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -284,7 +284,41 @@ fn rings_png() -> Vec<u8> {
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -64,7 +64,24 @@ fn one(s: &mut Session, p: Value) -> Vec<u8> {
|
||||
}
|
||||
|
||||
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 {
|
||||
|
||||
Loaded 100 of 279 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user