Merge pull request #7933 from dotCooCoo/fix/svg-import-png-keeps-icc-profile

SVG import: a raster stored again as PNG keeps its ICC profile
This commit is contained in:
BFlat
2026-11-16 04:27:48 +07:00
committed by GitHub
3 changed files with 166 additions and 11 deletions
+38 -11
View File
@@ -875,7 +875,8 @@ fn raster(format: image::ImageFormat) -> Option<RasterKind> {
/// TIFF) leaves the pixels as stored. Otherwise the pixels are read ([`decoded`],
/// [`tiff_pixels`]), turned or flipped as the orientation says, and written as PNG, so usvg sizes
/// and fits the image as it is shown, with the resolution the file declares
/// ([`vectorcraft_doc::ppi::resolution`]), its axes swapped by a quarter turn. A CMYK TIFF also
/// ([`vectorcraft_doc::ppi::resolution`]), its axes swapped by a quarter turn, and the ICC profile
/// the file carries when its color space is the written samples' (gray or RGB). A CMYK TIFF also
/// keeps its inks as a CMYK TIFF ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]), and a CMYK JPEG
/// or TIFF that is turned keeps them turned ([`vectorcraft_doc::cmyk::turned_cmyk`]). `None` when
/// the pixels can't be read, and for a TIFF with more strips or tiles than the decoder can count
@@ -893,7 +894,7 @@ fn shown(bytes: Arc<Vec<u8>>, format: image::ImageFormat) -> Option<Shown> {
return Some(Shown { kind, bytes, cmyk: None });
}
let tiff = image::guess_format(&bytes).ok() == Some(F::Tiff);
let mut img = if tiff { tiff_pixels(&bytes)? } else { decoded(&bytes, format)? };
let (mut img, icc) = if tiff { tiff_pixels(&bytes)? } else { decoded(&bytes, format)? };
let ppi = vectorcraft_doc::ppi::resolution(&bytes);
// The resolution describes the stored pixels; a quarter turn swaps its axes.
let quarter = orientation.is_some_and(|o| o.to_exif() >= 5);
@@ -906,18 +907,38 @@ fn shown(bytes: Arc<Vec<u8>>, format: image::ImageFormat) -> Option<Shown> {
if let Some(orientation) = orientation {
img.apply_orientation(orientation);
}
use image::DynamicImage as D;
let img = match img {
D::ImageLuma8(_) | D::ImageLumaA8(_) | D::ImageRgb8(_) | D::ImageRgba8(_) => img,
D::ImageLuma16(_) | D::ImageLumaA16(_) | D::ImageRgb16(_) | D::ImageRgba16(_) => img,
other => D::ImageRgba8(other.into_rgba8()),
};
let mut png = Vec::new();
img.write_to(&mut std::io::Cursor::new(&mut png), F::Png).ok()?;
let mut encoder = image::codecs::png::PngEncoder::new(&mut png);
if let Some(icc) = icc.filter(|icc| png_takes_icc(&img, icc)) {
// A profile the encoder doesn't take leaves the image without one.
let _ = image::ImageEncoder::set_icc_profile(&mut encoder, icc);
}
img.write_with_encoder(encoder).ok()?;
if let Some(ppi) = shown_ppi {
png = vectorcraft_doc::ppi::with_png_resolution(&png, ppi);
}
Some(Shown { kind: ImageKind::PNG, bytes: Arc::new(png), cmyk })
}
/// Can a PNG of `img`'s samples carry ICC profile `icc`? Its color space must be the samples':
/// `GRAY` for gray samples, `RGB ` for RGB ones.
fn png_takes_icc(img: &image::DynamicImage, icc: &[u8]) -> bool {
let want = if img.color().has_color() { *b"RGB " } else { *b"GRAY" };
vectorcraft_doc::cmyk::icc_color_space(icc) == Some(want)
}
/// The pixels of encoded image `bytes` (`format` when their bytes don't say), as stored, decoded
/// within [`vectorcraft_doc::MAX_RASTER_ALLOC`], counted as decoded and as RGBA, as Open and Place
/// decode them; `None` when they can't be.
fn decoded(bytes: &[u8], format: image::ImageFormat) -> Option<image::DynamicImage> {
/// decode them, with the ICC profile their samples are in when the file carries one the decoder
/// can read (a TIFF's read by [`vectorcraft_doc::cmyk::tiff_icc_profile`]); `None` when they
/// can't be.
fn decoded(bytes: &[u8], format: image::ImageFormat) -> Option<(image::DynamicImage, Option<Vec<u8>>)> {
use image::ImageDecoder as _;
let max = vectorcraft_doc::MAX_RASTER_ALLOC;
let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?;
@@ -927,12 +948,16 @@ fn decoded(bytes: &[u8], format: image::ImageFormat) -> Option<image::DynamicIma
let mut limits = image::Limits::default();
limits.max_alloc = Some(max);
reader.limits(limits);
let decoder = reader.into_decoder().ok()?;
let tiff = reader.format() == Some(image::ImageFormat::Tiff);
let mut decoder = reader.into_decoder().ok()?;
let (w, h) = decoder.dimensions();
if decoder.total_bytes() > max || u64::from(w) * u64::from(h) * 4 > max {
return None;
}
image::DynamicImage::from_decoder(decoder).ok()
// 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 icc = if tiff { vectorcraft_doc::cmyk::tiff_icc_profile(bytes) } else { decoder.icc_profile().ok().flatten() };
Some((image::DynamicImage::from_decoder(decoder).ok()?, icc))
}
/// The pixels of TIFF `bytes`, as stored, read as Open and Place read them: a TIFF with extra
@@ -940,15 +965,17 @@ fn decoded(bytes: &[u8], format: image::ImageFormat) -> Option<image::DynamicIma
/// ([`vectorcraft_doc::cmyk::extra_samples_tiff_rgba`]); a 1-bit TIFF compressed with CCITT Group
/// 3 as RGBA ([`vectorcraft_doc::cmyk::group3_tiff_rgba`]); others by [`decoded`], a CMYK TIFF
/// that stores one plane per ink with its inks written together first
/// ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]). `None` when they can't be read.
fn tiff_pixels(bytes: &[u8]) -> Option<image::DynamicImage> {
/// ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]). Pixels the image decoder reads come with the
/// TIFF's ICC profile; the other readers give sRGB pixels, without one. `None` when they can't be
/// read.
fn tiff_pixels(bytes: &[u8]) -> Option<(image::DynamicImage, Option<Vec<u8>>)> {
use image::DynamicImage::ImageRgba8;
let cms = vectorcraft_color::cms::active();
if let Some(img) = vectorcraft_doc::cmyk::extra_samples_tiff_rgba(bytes, |c| cms.cmyk_to_srgb(c, false)) {
return Some(ImageRgba8(img));
return Some((ImageRgba8(img), None));
}
if let Some(read) = vectorcraft_doc::cmyk::group3_tiff_rgba(bytes) {
return read.ok().map(ImageRgba8);
return read.ok().map(|img| (ImageRgba8(img), None));
}
decoded(bytes, image::ImageFormat::Tiff).or_else(|| decoded(&vectorcraft_doc::cmyk::stored_cmyk_tiff(bytes, None)?, image::ImageFormat::Tiff))
}
+127
View File
@@ -362,6 +362,133 @@ fn a_cmyk_tiff_keeps_its_resolution_turned_or_not() {
}
}
/// A made-up ICC profile of `len` bytes (at least a header's 128) whose header names the color
/// space `space`; the bytes after the header differ from place to place.
fn icc_profile(space: &[u8; 4], len: usize) -> Vec<u8> {
let mut icc: Vec<u8> = (0..len).map(|i| (i % 251) as u8).collect();
icc[..4].copy_from_slice(&u32::try_from(len).unwrap().to_be_bytes());
icc[12..16].copy_from_slice(b"mntr");
icc[16..20].copy_from_slice(space);
icc[36..40].copy_from_slice(b"acsp");
icc
}
/// `tiff` (little-endian) with an ICCProfile tag (34675, of type UNDEFINED) holding `icc`: its first
/// directory copied to the end of the file with the tag added in order.
fn tiff_with_icc(tiff: &[u8], icc: &[u8]) -> Vec<u8> {
let at = usize::try_from(u32::from_le_bytes(tiff[4..8].try_into().unwrap())).unwrap();
let n = usize::from(u16::from_le_bytes([tiff[at], tiff[at + 1]]));
let mut entries: Vec<Vec<u8>> = tiff[at + 2..at + 2 + 12 * n].chunks(12).map(<[u8]>::to_vec).collect();
let mut out = tiff.to_vec();
if out.len() % 2 == 1 {
out.push(0);
}
let data = u32::try_from(out.len()).unwrap();
out.extend(icc);
if out.len() % 2 == 1 {
out.push(0);
}
let i = entries.iter().position(|e| u16::from_le_bytes([e[0], e[1]]) > 34675).unwrap_or(n);
let count = u32::try_from(icc.len()).unwrap();
entries.insert(i, [&34675u16.to_le_bytes()[..], &7u16.to_le_bytes(), &count.to_le_bytes(), &data.to_le_bytes()].concat());
let ifd = u32::try_from(out.len()).unwrap();
out[4..8].copy_from_slice(&ifd.to_le_bytes());
out.extend(u16::try_from(n + 1).unwrap().to_le_bytes());
out.extend(entries.concat());
out.extend([0; 4]);
out
}
/// A little-endian EXIF block (a TIFF header and one directory) giving Orientation `orientation`.
fn exif_block(orientation: u16) -> Vec<u8> {
let o = orientation.to_le_bytes();
[b"II".as_slice(), &[0x2a, 0, 8, 0, 0, 0], &[1, 0], &[0x12, 0x01, 3, 0, 1, 0, 0, 0, o[0], o[1], 0, 0], &[0, 0, 0, 0]].concat()
}
/// The ICC profile and the bits per sample of the PNG `im` is stored as.
fn stored_icc(d: &Document, im: &ImageObject) -> (Option<Vec<u8>>, u16) {
use image::ImageDecoder as _;
let blob = &d.images[&im.key];
assert_eq!(blob.mime, "image/png");
let mut dec = image::codecs::png::PngDecoder::new(std::io::Cursor::new(blob.bytes.as_slice())).unwrap();
let color = dec.original_color_type();
(dec.icc_profile().unwrap(), color.bits_per_pixel() / u16::from(color.channel_count()))
}
/// A raster that import writes again as PNG keeps the gray or RGB ICC profile its file carries,
/// byte for byte, linked and as a data URL: a TIFF, turned or not, and a turned PNG and JPEG, with
/// 16-bit samples kept at 16 bits and the resolution kept beside the profile. A profile of another
/// color space than the written samples', one too short to be a profile, and one on a TIFF whose
/// pixels are read as RGBA by its own reader are left out, and the image still imports.
#[test]
fn a_raster_written_again_as_png_keeps_its_icc_profile() {
use image::{DynamicImage, ImageEncoder as _};
let (rgb_icc, gray_icc, cmyk_icc) = (icc_profile(b"RGB ", 600), icc_profile(b"GRAY", 300), icc_profile(b"CMYK", 400));
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 gray8 = DynamicImage::ImageLuma8(image::GrayImage::from_fn(3, 2, |x, y| image::Luma([u8::try_from(x * 80 + y * 7).unwrap()])));
let rgb16 = DynamicImage::ImageRgb16(image::ImageBuffer::from_fn(3, 2, |x, y| {
let v = u16::try_from(x * 0x1111 + y * 0x2345).unwrap();
image::Rgb([0x1000 + v, 0x8001 + v, 0xF0F3 - v])
}));
let tiff_of = |img: &DynamicImage, icc: &[u8]| {
let mut out = Vec::new();
let mut enc = image::codecs::tiff::TiffEncoder::new(std::io::Cursor::new(&mut out));
enc.set_icc_profile(icc.to_vec()).unwrap();
img.write_with_encoder(enc).unwrap();
out
};
let png = {
let mut out = Vec::new();
let mut enc = image::codecs::png::PngEncoder::new(&mut out);
enc.set_icc_profile(rgb_icc.clone()).unwrap();
enc.set_exif_metadata(exif_block(6)).unwrap();
rgb16.write_with_encoder(enc).unwrap();
out
};
let jpg = {
let mut out = Vec::new();
let mut enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 95);
enc.set_icc_profile(rgb_icc.clone()).unwrap();
rgb8.write_with_encoder(enc).unwrap();
let exif = [b"Exif\0\0".as_slice(), &exif_block(6)].concat();
let mut turned = out[..2].to_vec();
turned.extend([0xff, 0xe1]);
turned.extend(u16::try_from(exif.len() + 2).unwrap().to_be_bytes());
turned.extend(&exif);
turned.extend(&out[2..]);
turned
};
let gray = [0, 0, 255, 255, 0, 0, 255, 255];
let turned_gray = tiff_with_icc(&tiff_at(4, 2, 1, &gray, 6, Some((300, 150))), &gray_icc);
let gray_alpha = [0, 255, 0, 255, 255, 255, 255, 255, 0, 255, 0, 255, 255, 255, 255, 255];
// (what, file, the ICC profile to keep, bits per sample, resolution)
type Case<'a> = (&'a str, Vec<u8>, Option<&'a [u8]>, u16, Option<(f64, f64)>);
let cases: Vec<Case> = vec![
("RGB TIFF", tiff_of(&rgb8, &rgb_icc), Some(&rgb_icc), 8, None),
("gray TIFF", tiff_of(&gray8, &gray_icc), Some(&gray_icc), 8, None),
("16-bit RGB TIFF", tiff_of(&rgb16, &rgb_icc), Some(&rgb_icc), 16, None),
("gray TIFF, orientation 6, with a resolution", turned_gray, Some(&gray_icc), 8, Some((150.0, 300.0))),
("16-bit RGB PNG, orientation 6", png, Some(&rgb_icc), 16, None),
("JPEG, orientation 6", jpg, Some(&rgb_icc), 8, None),
("RGB TIFF with a gray profile", tiff_of(&rgb8, &gray_icc), None, 8, None),
("gray TIFF with an RGB profile", tiff_of(&gray8, &rgb_icc), None, 8, None),
("RGB TIFF with a CMYK profile", tiff_of(&rgb8, &cmyk_icc), None, 8, None),
("RGB TIFF with a profile too short to be one", tiff_of(&rgb8, &rgb_icc[..40]), None, 8, None),
("gray TIFF with alpha, read as RGBA", tiff_with_icc(&tiff(4, 2, 2, &gray_alpha, 1), &rgb_icc), None, 8, None),
];
let dir = folder("icc");
for (what, file, icc, bits, ppi) in cases {
std::fs::write(dir.join("photo.img"), &file).unwrap();
let data = format!("data:;base64,{}", base64_encode(&file));
for href in ["photo.img", data.as_str()] {
let what = format!("{what}, {}", &href[..href.len().min(12)]);
let (d, im) = import_one(&format!(r#"<image href="{href}" width="20" height="40"/>"#), Some(&dir));
assert_eq!(stored_icc(&d, &im), (icc.map(<[u8]>::to_vec), bits), "{what}");
assert_eq!(stored_ppi(&d, &im), ppi, "{what}");
}
}
}
/// A turned JPEG that a linked SVG file links to is turned too.
#[test]
fn a_turned_jpeg_linked_from_a_linked_svg_file_imports_upright() {
+1
View File
@@ -1952,6 +1952,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- PDF export with Output › Convert to Destination and a CMYK destination, or an RGB destination other than sRGB that images are converted to, converts an RGB image that carries an ICC profile from that profile to sRGB and then to the destination, with the color settings' rendering intent, instead of reading its numbers as sRGB ([PDF options](https://helpx.adobe.com/illustrator/using/pdf-options.html)). An untagged image converts from sRGB as before, a gray image keeps its profile, and a profile the color engine can't read leaves the numbers read as sRGB, with a warning. An RGB destination other than sRGB that is the document's own RGB profile leaves RGB colors and RGB images as they are, so a tagged RGB image keeps its profile there (`convert_to_destination_converts_tagged_images_from_their_profile` in `crates/pdf/src/tests/compression.rs`).
- SVG import shows a raster `<image>` whose EXIF orientation or TIFF Orientation tag turns or flips it upright, linked or as a data URL, and inside an SVG shown as an image: the pixels are stored turned, the width and height swap, and the `<image>` box fits the turned image under `preserveAspectRatio`, as CSS `image-orientation: from-image` describes (<https://www.w3.org/TR/css-images-3/#the-image-orientation>). A turned CMYK JPEG or TIFF keeps its inks as a CMYK TIFF, as does a CMYK TIFF that is not turned. TIFF data URLs (`image/tiff`, or untyped TIFF bytes) are read, and TIFFs with an alpha or other extra channel, CCITT Group 3 TIFFs and CMYK TIFFs stored one plane per ink are read as Open and Place read them. The pixels are decoded within the decode allowance, and a TIFF claiming more strips or tiles than the decoder can count is refused before it is decoded (`crates/svg/tests/it/image_orientation.rs`).
- An image that SVG import stores again, as PNG or as a CMYK TIFF, keeps the resolution its PNG, JPEG, TIFF, WebP or BMP file declares, as Open and Place keep it: in a PNG `pHYs` chunk (<https://www.w3.org/TR/png-3/#11pHYs>) or the TIFF's resolution tags, with the horizontal and vertical values swapped when the image turns a quarter. An image that declares no resolution is stored without one (`a_turned_raster_keeps_its_resolution`, `an_upright_tiff_keeps_its_resolution` and `a_cmyk_tiff_keeps_its_resolution_turned_or_not` in `crates/svg/tests/it/image_orientation.rs`).
- An image that SVG import stores again as PNG keeps the ICC profile its TIFF, PNG, JPEG or WebP file carries, as Open and Place keep it, as a PNG `iCCP` chunk, when the profile's color space is the stored samples': gray for gray samples, RGB for RGB ones (<https://www.w3.org/TR/png-3/#11iCCP>). By default, SVG reads an image's colors in the profile built into the image (<https://www.w3.org/TR/SVG11/color.html#ColorProfileProperty>). A profile of another color space, one too short to be a profile, and the profile of a TIFF whose pixels its own reader converts to RGBA (one with an alpha or other extra channel, or CCITT Group 3) are left out, and the image is still imported (`a_raster_written_again_as_png_keeps_its_icc_profile` in `crates/svg/tests/it/image_orientation.rs`).
- SVG import leaves out an SVG shown as an image that it can't read (text that isn't XML, an SVG without a size) and goes on with the images after it, as SVG 2's error processing describes (<https://www.w3.org/TR/SVG2/conform.html>). Only images that decode count toward the 256 nested SVG images an SVG may show, so an image after many broken ones is imported. Every nested SVG image read, decoded or not, counts toward VectorCraft's own limits of 1,024 reads and 512 MB of text per import; past them, nested SVG images are left out with a warning (`crates/svg/tests/it/import_details.rs`).
- SVG import decodes each image data URL (RFC 2397, <https://www.rfc-editor.org/rfc/rfc2397#section-2>) of an `<image>` or `<feImage>` once, in the imported SVG and in the SVGs shown as its images, however many `<use>` elements, filters or SVG images show it; every use gets the same image. The data URLs of one import decode to at most 512 MB together, VectorCraft's own limit: decoding stops where a URL would pass it, and that image is left out with a warning (`crates/svg/src/import/files.rs`, `crates/svg/tests/it/import_details.rs`).
- SVG import measures what an SVG expands to before the SVG reader builds it: every copy a `<use>` shows (<https://www.w3.org/TR/SVG2/struct.html#UseElement>), chains of `<use>`s included, and the style values each copy gets from its `style` attribute and from the style sheet rules that match it. An SVG that expands to more than 999,999 elements (500,000 on the web) or to more than 64 MB of copied style values is refused with an error, and so is a loop of `<use>` references that would be copied without end. The declarations the import's own style cascade keeps count toward the 64 MB too, once for each element a rule matches, including those of rules the reader drops, such as ones with `:not()`. Matching the style sheets' selectors against those elements may take at most 50,000,000 tests; past that the SVG is refused, so a selector that never matches can't keep the import busy. These limits are VectorCraft's own. An SVG shown as an image, from a data URL or a linked SVG file, counts toward the same limits as the SVG showing it, and one past any of them refuses the whole import (`crates/svg/src/import/budget.rs`, `crates/svg/tests/it/import_details.rs`).