Merge pull request #3375 from AlPaka1234/fix/3341-pdf-x4-icc-image

PDF/X-4: keep placed RGB images ICCBased when embedded ICC is dropped by PDF 1.6 (#3341)
This commit is contained in:
FredApps authored and GitHub committed 2026-12-01 10:49:12 +01:00
commit 177ad1fac1
5 files changed
+321 -36

No files matched your search

+18 -5
View File
@@ -68,7 +68,7 @@ pub fn to_display_rgba(px: Pixels, embedded_icc: Option<&[u8]>, display: &Displa
if let Some(x) = own(ColorSpace::Rgb)
&& !keeps_rgb(&x)
{
in_place(&mut img, &x);
let _ = in_place(&mut img, &x);
}
Some(img)
}
@@ -76,7 +76,7 @@ pub fn to_display_rgba(px: Pixels, embedded_icc: Option<&[u8]>, display: &Displa
if let Some(x) = own(ColorSpace::Gray)
&& !keeps_gray(&x)
{
in_place(&mut img, &x);
let _ = in_place(&mut img, &x);
}
Some(img)
}
@@ -87,6 +87,18 @@ pub fn to_display_rgba(px: Pixels, embedded_icc: Option<&[u8]>, display: &Displa
}
}
/// Convert straight RGBA8 pixels from `embedded_icc` into sRGB, returning `None` if the profile
/// cannot be parsed as RGB, yields no usable RGB → sRGB transform, or fails during pixel
/// conversion. Unlike [`to_display_rgba`], never falls back to unconverted pixels.
pub fn convert_rgb_to_srgb(mut img: RgbaImage, embedded_icc: &[u8], display: &DisplayColour) -> Option<RgbaImage> {
let profile = parse(embedded_icc, ColorSpace::Rgb)?;
let x = to_srgb(&profile, display.options)?;
if !keeps_rgb(&x) && !in_place(&mut img, &x) {
return None;
}
Some(img)
}
fn parse(icc: &[u8], pixels: ColorSpace) -> Option<Profile> {
if icc.len() > MAX_ICC_BYTES {
log::warn!("embedded ICC profile of {} bytes is too large: ignored", icc.len());
@@ -149,16 +161,17 @@ fn keeps_gray(x: &Transform) -> bool {
}
/// Convert RGBA pixels whose first channels (RGB, or grey for a grey transform) hold the source
/// values; alpha is kept.
fn in_place(img: &mut RgbaImage, x: &Transform) {
/// values; alpha is kept. Returns `false` if any chunk fails to convert.
fn in_place(img: &mut RgbaImage, x: &Transform) -> bool {
let mut src = Vec::with_capacity(CHUNK * 4);
for chunk in img.chunks_mut(CHUNK * 4) {
src.clear();
src.extend_from_slice(chunk);
if !convert(x, &src, 4, chunk, 4) {
return;
return false;
}
}
true
}
/// CMYK inks → RGBA through `x`, or the profile-free formula without one.
+13
View File
@@ -413,6 +413,19 @@ pub fn decode_rgba(bytes: &[u8]) -> Option<image::RgbaImage> {
to_display_rgba(px, Some(icc), &DisplayColour::active())
}
/// Straight RGBA8 of an RGB raster decoded under the normal RGBA budget and strictly converted
/// from `icc` to sRGB. Returns `None` if decoding fails, the image exceeds the decode budget, or
/// `icc` yields no usable RGB → sRGB conversion (unlike [`decode_rgba`], never falls back to
/// unconverted RGB).
pub fn decode_rgb_to_srgb(bytes: &[u8], icc: &[u8]) -> Option<image::RgbaImage> {
if too_large_to_decode(bytes) {
return None;
}
let decoded = craft_image_codecs::decode_with(bytes, &decode_options()).ok()?;
let rgba = image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8())?;
colour::convert_rgb_to_srgb(rgba, icc, &colour::DisplayColour::active())
}
/// About how many bytes a pixel [`decode_rgba`] of `bytes` holds at once, with a premultiplied
/// copy of its result. A decode holds the samples as decoded beside the 8-bit RGBA (or, for
/// CMYK, the 8-bit CMYKA copy and its ink and alpha planes) they are converted to, or two copies
+134 -27
View File
@@ -58,6 +58,34 @@ pub(super) fn is_grey_icc(icc: &[u8]) -> bool {
icc.get(16..20) == Some(b"GRAY".as_slice())
}
/// Whether an ICC profile describes CMYK.
fn is_cmyk_icc(icc: &[u8]) -> bool {
icc.get(16..20) == Some(b"CMYK".as_slice())
}
/// Whether krilla embeds `icc` as `/ICCBased` in a PDF 1.6 (PDF/X-4) file.
///
/// krilla's `PdfVersion::Pdf16::supports_icc` checks `major <= 4 && minor <= 1`, so ICC v2.2–2.4
/// and v4.2+ profiles (such as LittleCMS/Pillow sRGB v4.4 or sRGB2014 v2.4) are dropped to
/// `/DeviceRGB` if passed through unchanged.
fn pdf16_accepts_icc(icc: &[u8]) -> bool {
icc.get(8).is_some_and(|&major| major <= 4) && icc.get(9).is_some_and(|&minor| (minor >> 4) <= 1)
}
/// Whether krilla embeds `icc` as an RGB `/ICCBased` space in PDF 1.6.
fn pdf16_accepts_rgb_icc(icc: &[u8]) -> bool {
is_rgb_icc(icc) && pdf16_accepts_icc(icc)
}
/// Whether `icc` is a readable RGB profile whose colours differ from sRGB (e.g. Display P3 or
/// Adobe RGB), so tagging raw pixels with `SRGB_ICC` without converting them would shift colour.
fn needs_srgb_conversion(icc: &[u8]) -> bool {
is_rgb_icc(icc)
&& icc.len() <= designcraft_images::colour::MAX_ICC_BYTES
&& craft_cms::Profile::parse(icc)
.is_ok_and(|p| p.color_space == craft_cms::ColorSpace::Rgb && !p.same_colors(craft_cms::Builtin::Srgb.profile()))
}
/// Whether `data` decodes to grey (with or without alpha), read from its header.
pub(super) fn is_grey(data: &[u8]) -> bool {
craft_image_codecs::inspect_raster(data).ok().flatten().is_some_and(|info| {
@@ -68,39 +96,57 @@ pub(super) fn is_grey(data: &[u8]) -> bool {
})
}
/// A JPEG, passed through. With `tag_rgb`, a JPEG keeps its own profile, and one without gets
/// sRGB. krilla uses a profile only when its channels match the JPEG's, so a grey or CMYK JPEG
/// without a profile stays DeviceGray or DeviceCMYK.
/// A JPEG, passed through. With `tag_rgb`, a JPEG keeps its own profile when PDF 1.6 accepts it
/// and its colour space matches the JPEG's channels; an RGB JPEG whose profile PDF 1.6 drops is
/// tagged with sRGB (after converting pixels to sRGB if the profile isn't sRGB), and an untagged
/// RGB JPEG gets sRGB. Grey and CMYK JPEGs without an accepted matching profile stay DeviceGray
/// or DeviceCMYK.
pub(super) fn jpeg(data: krilla::Data, icc: impl FnOnce() -> Option<Vec<u8>>, mode: RasterMode) -> Option<Image> {
if !mode.tag_rgb {
return Image::from_jpeg(data, mode.interpolate).ok();
}
let icc: krilla::Data = match icc() {
Some(own) => own.into(),
None => SRGB_ICC.into(),
};
Image::from_jpeg_with_icc(data, Some(icc), mode.interpolate).ok()
}
/// Whether krilla would write this PNG, GIF or WebP as untagged RGB: not grey, and no profile of
/// its own. The header inspection doesn't read WebP, which has no grey form, so a file it can't
/// read counts as colour.
fn untagged_rgb(data: &[u8]) -> bool {
!is_grey(data) && embedded_icc(data).is_none()
let color = craft_image_codecs::inspect_raster(data.as_ref()).ok().flatten().map(|info| info.color_type);
let own = icc();
let keep_own = own.as_deref().is_some_and(|p| {
pdf16_accepts_icc(p)
&& match color {
Some(craft_image_codecs::RasterColorType::Gray | craft_image_codecs::RasterColorType::Bitmap) => is_grey_icc(p),
Some(craft_image_codecs::RasterColorType::Cmyk) => is_cmyk_icc(p),
_ => is_rgb_icc(p),
}
});
if keep_own {
return Image::from_jpeg_with_icc(data, own.map(Into::into), mode.interpolate).ok();
}
let is_rgb = !matches!(
color,
Some(craft_image_codecs::RasterColorType::Gray | craft_image_codecs::RasterColorType::Bitmap | craft_image_codecs::RasterColorType::Cmyk)
);
if is_rgb && let Some(p) = own.as_deref().filter(|p| needs_srgb_conversion(p)) {
let rgba = designcraft_images::decode_rgb_to_srgb(data.as_ref(), p)?;
return SrgbImage::new(rgba).and_then(|img| Image::from_custom(img, mode.interpolate).ok());
}
Image::from_jpeg_with_icc(data, Some(SRGB_ICC.into()), mode.interpolate).ok()
}
pub(super) fn lossless(data: &Arc<Vec<u8>>, fmt: Option<craft_image_codecs::Format>, mode: RasterMode) -> Option<Image> {
if designcraft_images::too_large_to_decode(data) {
return None;
}
let i = mode.interpolate;
let direct_format = matches!(fmt, Some(craft_image_codecs::Format::Png | craft_image_codecs::Format::Gif | craft_image_codecs::Format::WebP));
let own_icc = if mode.tag_rgb { embedded_icc(data) } else { None };
let will_tag_srgb = mode.tag_rgb && !is_grey(data) && !(direct_format && own_icc.as_deref().is_some_and(pdf16_accepts_rgb_icc));
// krilla reads PNG, GIF and WebP lazily: a damaged file is accepted here and fails the whole
// export when the PDF is written. Decoding it first means it is skipped, like any other
// image that can't be decoded.
let rgba = designcraft_images::decode_rgba(data)?;
let i = mode.interpolate;
let rgba = if will_tag_srgb && let Some(icc) = own_icc.as_deref().filter(|p| needs_srgb_conversion(p)) {
designcraft_images::decode_rgb_to_srgb(data, icc)?
} else {
designcraft_images::decode_rgba(data)?
};
let direct = match fmt {
Some(craft_image_codecs::Format::Png | craft_image_codecs::Format::Gif | craft_image_codecs::Format::WebP)
if mode.tag_rgb && untagged_rgb(data) =>
{
None
}
Some(craft_image_codecs::Format::Png | craft_image_codecs::Format::Gif | craft_image_codecs::Format::WebP) if will_tag_srgb => None,
Some(craft_image_codecs::Format::Png) => Image::from_png(data.clone().into(), i).ok(),
Some(craft_image_codecs::Format::Gif) => Image::from_gif(data.clone().into(), i).ok(),
Some(craft_image_codecs::Format::WebP) => Image::from_webp(data.clone().into(), i).ok(),
@@ -113,6 +159,11 @@ pub(super) fn lossless(data: &Arc<Vec<u8>>, fmt: Option<craft_image_codecs::Form
}
// TIFF, BMP, PSD composites… and, with `tag_rgb`, untagged RGB.
if mode.tag_rgb {
let rgba = if !will_tag_srgb && let Some(icc) = own_icc.as_deref().filter(|p| needs_srgb_conversion(p)) {
designcraft_images::decode_rgb_to_srgb(data, icc)?
} else {
rgba
};
return SrgbImage::new(rgba).and_then(|img| Image::from_custom(img, i).ok());
}
let (w, h) = rgba.dimensions();
@@ -165,7 +216,8 @@ thread_local! {
}
/// Opaque raster → JPEG (quality 90). `None` when the image has transparency, is too large or
/// can't be decoded. With `tag_rgb`, the JPEG keeps the source's RGB profile, or gets sRGB.
/// can't be decoded. With `tag_rgb`, the JPEG keeps the source's profile when PDF 1.6 accepts it,
/// or converts/tags to sRGB.
pub(super) fn recompress(data: &[u8], mode: RasterMode) -> Option<Image> {
if designcraft_images::too_large_to_decode(data) {
return None;
@@ -181,14 +233,40 @@ pub(super) fn recompress(data: &[u8], mode: RasterMode) -> Option<Image> {
}
// A grey image stays a grey JPEG (#1426).
let grey = img.layout().is_gray();
let jpeg_image = if grey {
img.convert(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8)
let icc = img.icc.as_deref();
let (jpeg_image, out_icc) = if grey {
(
img.convert(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8),
mode.tag_rgb.then(|| icc.filter(|p| is_grey_icc(p) && pdf16_accepts_icc(p)).map(<[u8]>::to_vec)).flatten(),
)
} else if mode.tag_rgb
&& let Some(icc) = icc.filter(|p| !pdf16_accepts_rgb_icc(p) && needs_srgb_conversion(p))
{
let rgba_img = image::RgbaImage::from_raw(img.width(), img.height(), rgba)?;
let converted = designcraft_images::colour::convert_rgb_to_srgb(rgba_img, icc, &designcraft_images::colour::DisplayColour::active())?;
let pixels = usize::try_from(converted.width()).ok()?.checked_mul(usize::try_from(converted.height()).ok()?)?;
let mut rgb = Vec::with_capacity(pixels.checked_mul(3)?);
for p in converted.pixels() {
rgb.extend_from_slice(&p.0[..3]);
}
let converted_img = craft_image_codecs::Image::from_raw(
converted.width(),
converted.height(),
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U8,
rgb,
)
.ok()?;
(converted_img, None)
} else {
img.convert(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8)
(
img.convert(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8),
mode.tag_rgb.then(|| icc.filter(|p| is_rgb_icc(p) && pdf16_accepts_icc(p)).map(<[u8]>::to_vec)).flatten(),
)
};
let options = craft_image_codecs::EncodeOptions { jpeg_quality: 90, ..Default::default() };
let buf = craft_image_codecs::encode(&jpeg_image, craft_image_codecs::Format::Jpeg, &options).ok()?;
jpeg(buf.into(), || embedded_icc(data).filter(|p| if grey { is_grey_icc(p) } else { is_rgb_icc(p) }), mode)
jpeg(buf.into(), || out_icc, mode)
}
#[cfg(test)]
@@ -563,4 +641,33 @@ mod recompress_tests {
assert!(recompress(&crate::tests::blank_png(9), mode).is_some());
assert_eq!(decodes(), start + 1);
}
/// A wide-gamut RGB JPEG whose embedded profile PDF 1.6 drops cannot be silently tagged as
/// sRGB when `decode_rgba` fails; an sRGB-equivalent JPEG still passes through without decoding.
#[test]
fn wide_gamut_jpeg_conversion_failure_does_not_fall_back_to_srgb_passthrough() {
let img = craft_image_codecs::Image::from_raw(
4,
2,
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U8,
[60, 200, 60].repeat(8),
)
.unwrap();
let mut bad_scan = craft_image_codecs::encode(&img, craft_image_codecs::Format::Jpeg, &Default::default()).unwrap();
// Truncate right after the SOS header so header-only parsers succeed while full decode fails.
let sos = bad_scan.windows(2).position(|w| w == [0xFF, 0xDA]).unwrap();
let sos_len = usize::from(u16::from_be_bytes([bad_scan[sos + 2], bad_scan[sos + 3]]));
bad_scan.truncate(sos + 2 + sos_len);
assert!(designcraft_images::decode_rgba(&bad_scan).is_none());
let mode = RasterMode { interpolate: false, tag_rgb: true };
let p3 = craft_cms::Builtin::DisplayP3.profile().clone().with_encoded_bytes().to_bytes().to_vec();
assert!(jpeg(bad_scan.clone().into(), || Some(p3), mode).is_none());
let mut srgb_v44 = craft_cms::Builtin::Srgb.profile().clone().with_encoded_bytes().to_bytes().to_vec();
srgb_v44[8] = 4;
srgb_v44[9] = 0x40;
assert!(jpeg(bad_scan.into(), || Some(srgb_v44), mode).is_some());
}
}
+2 -2
View File
@@ -21,8 +21,8 @@
//! Appearance of Black says so) as `/op` and `/OP` with `/OPM 1`; left out of PDF/A.
//! - **Images:** clipped to their frame; JPEG data is passed through, PNG/GIF/WebP are embedded
//! losslessly (or re-encoded as JPEG with [`PdfOptions::compress_images`]). PDF/X-4 and PDF/A
//! images are written without interpolation. In PDF/X-4 an RGB image without a profile of its own
//! carries sRGB (`assets/icc/sRGB-v2-magic.icc`).
//! images are written without interpolation. In PDF/X-4 an RGB image without a PDF 1.6-compatible
//! profile of its own carries sRGB (`assets/icc/sRGB-v2-magic.icc`).
//! - **Text as real text:** the composed glyph runs are emitted with embedded, subsetted fonts and a
//! Unicode mapping taken from the story text (ligatures, page numbers and inserted hyphens get the
//! right characters), so text is selectable and searchable.
+154 -2
View File
@@ -407,9 +407,161 @@ fn own_profiles_and_grey_stay() {
let mut d = Document::new(&NewDocument::default());
place(&mut d, "grey.png", png(true, None), (4.0, 2.0), (72.0, 72.0));
place(&mut d, "tagged.png", png(false, Some(rgb_icc())), (4.0, 2.0), (72.0, 172.0));
place(&mut d, "tagged.jpg", encode_with_icc(craft_image_codecs::Format::Jpeg, false, [0, 128, 255, 255], rgb_icc()), (4.0, 2.0), (72.0, 272.0));
let r = x4(&d);
assert_eq!(image_spaces(&r.bytes), ["DeviceGray", "[ICCBased"]);
assert_eq!(image_profiles(&r.bytes), [rgb_icc()]);
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
assert_eq!(image_spaces(&r.bytes), ["DeviceGray", "[ICCBased", "[ICCBased"]);
assert_eq!(image_profiles(&r.bytes), [rgb_icc(), rgb_icc()]);
}
/// Encode a 4 × 2 RGB or RGBA image with `icc` embedded in `format`.
fn encode_with_icc(format: craft_image_codecs::Format, rgba: bool, color: [u8; 4], icc: Vec<u8>) -> Vec<u8> {
let (layout, pixels) = if rgba {
(craft_image_codecs::ChannelLayout::Rgba, color.repeat(8))
} else {
(craft_image_codecs::ChannelLayout::Rgb, [color[0], color[1], color[2]].repeat(8))
};
let img = craft_image_codecs::Image::from_raw(4, 2, layout, craft_image_codecs::SampleType::U8, pixels).unwrap().with_icc(Some(icc));
let opts = craft_image_codecs::EncodeOptions { embed_icc: true, ..Default::default() };
craft_image_codecs::encode(&img, format, &opts).unwrap()
}
/// Placed RGB/RGBA images with an embedded sRGB profile whose ICC version PDF 1.6 / krilla drops
/// (v2.4, v4.2, v4.3, v4.4) or a mismatched profile must still be written as `/ICCBased` in
/// PDF/X-4 rather than falling back to `/DeviceRGB` (#3341).
#[test]
fn embedded_srgb_icc_past_pdf16_stays_iccbased_in_pdfx4() {
let srgb_v44 = {
let mut p = craft_cms::Builtin::Srgb.profile().clone().with_encoded_bytes().to_bytes().to_vec();
p[8] = 4;
p[9] = 0x40;
p
};
let srgb_v24 = {
let mut p = crate::export::SRGB_ICC.to_vec();
p[8] = 2;
p[9] = 0x40;
p
};
let mut wrong_space = rgb_icc();
wrong_space[16..20].copy_from_slice(b"GRAY");
let mut d = Document::new(&NewDocument::default());
let cases = [
("srgb-v44.jpg", encode_with_icc(craft_image_codecs::Format::Jpeg, false, [200, 40, 20, 255], srgb_v44.clone())),
("srgb-v24.jpg", encode_with_icc(craft_image_codecs::Format::Jpeg, false, [20, 200, 40, 255], srgb_v24.clone())),
("srgb-v44.png", encode_with_icc(craft_image_codecs::Format::Png, false, [40, 20, 200, 255], srgb_v44.clone())),
("srgb-v44-alpha.png", encode_with_icc(craft_image_codecs::Format::Png, true, [200, 180, 20, 128], srgb_v44.clone())),
("srgb-v44.webp", encode_with_icc(craft_image_codecs::Format::WebP, false, [20, 180, 200, 255], srgb_v44)),
("wrong-icc.jpg", encode_with_icc(craft_image_codecs::Format::Jpeg, false, [180, 20, 180, 255], wrong_space.clone())),
("wrong-icc.png", encode_with_icc(craft_image_codecs::Format::Png, false, [120, 90, 60, 255], wrong_space)),
];
for (i, (name, data)) in cases.into_iter().enumerate() {
place(&mut d, name, data, (4.0, 2.0), (72.0, 72.0 + 40.0 * i as f64));
}
for compress_images in [false, true] {
let opts = PdfOptions { standard: Standard::PdfX4, compress_images, ..Default::default() };
let r = export_pdf_with_report(&d, &Cache::new(), &opts).unwrap();
assert!(r.warnings.is_empty(), "compress_images {compress_images}: {:?}", r.warnings);
assert!(check_pdfx4(&r.bytes).is_empty(), "compress_images {compress_images}: {:?}", check_pdfx4(&r.bytes));
// 7 colour images (all ICCBased) + 1 DeviceGray SMask for the RGBA PNG.
let mut expected = vec!["DeviceGray".to_string()];
expected.extend(std::iter::repeat_n("[ICCBased".to_string(), 7));
expected.sort();
assert_eq!(image_spaces(&r.bytes), expected, "compress_images {compress_images}");
let profiles = image_profiles(&r.bytes);
assert_eq!(profiles.len(), 7, "compress_images {compress_images}");
assert!(profiles.iter().all(|p| p == crate::export::SRGB_ICC), "fallback profile is sRGB v2.1");
}
// sRGB v4.4 JPEG keeps DCTDecode passthrough without re-encoding.
let mut single = Document::new(&NewDocument::default());
let jpg = encode_with_icc(craft_image_codecs::Format::Jpeg, false, [200, 40, 20, 255], srgb_v24);
place(&mut single, "srgb-v24.jpg", jpg, (4.0, 2.0), (72.0, 72.0));
let r = x4(&single);
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
assert!(String::from_utf8_lossy(&r.bytes).contains("/DCTDecode"), "sRGB JPEG keeps DCTDecode passthrough");
}
/// A wide-gamut RGB image whose embedded ICC version PDF 1.6 / krilla drops (e.g. Display P3 v4.3)
/// is converted to sRGB pixels before being tagged with sRGB v2.1, so colours are not shifted.
#[test]
fn embedded_wide_gamut_icc_past_pdf16_converts_to_srgb_in_pdfx4() {
let p3 = craft_cms::Builtin::DisplayP3.profile().clone().with_encoded_bytes().to_bytes().to_vec();
let src_color = [60, 200, 60, 255];
let p3_png = encode_with_icc(craft_image_codecs::Format::Png, false, src_color, p3.clone());
let p3_jpg = encode_with_icc(craft_image_codecs::Format::Jpeg, false, src_color, p3);
let expected_srgb = designcraft_images::decode_rgba(&p3_png).unwrap().get_pixel(0, 0).0;
// Sanity: Display P3 green shifts noticeably when converted to sRGB.
assert!(expected_srgb[0].abs_diff(src_color[0]) > 10 || expected_srgb[1].abs_diff(src_color[1]) > 5);
for (name, bytes) in [("p3.png", p3_png), ("p3.jpg", p3_jpg)] {
let mut d = Document::new(&NewDocument::default());
place(&mut d, name, bytes, (4.0, 2.0), (72.0, 72.0));
for compress_images in [false, true] {
let opts = PdfOptions { standard: Standard::PdfX4, compress_images, ..Default::default() };
let r = export_pdf_with_report(&d, &Cache::new(), &opts).unwrap();
assert!(r.warnings.is_empty(), "{name} compress={compress_images}: {:?}", r.warnings);
assert_eq!(image_spaces(&r.bytes), ["[ICCBased"], "{name} compress={compress_images}");
assert_eq!(image_profiles(&r.bytes), [crate::export::SRGB_ICC], "{name} compress={compress_images}");
// Decode the written image stream (either raw RGB8 or JPEG) and verify sRGB conversion.
let pdf = craft_pdf::syntax::Pdf::new(r.bytes).unwrap();
let stream = pdf
.objects()
.into_iter()
.filter_map(|o| o.into_stream())
.find(|s| s.dict().get::<Name>(b"Subtype").is_some_and(|n| n.as_str() == "Image"))
.unwrap();
let px = if stream.dict().get::<Name>(b"Filter").is_some_and(|f| f.as_str() == "DCTDecode") {
let raw_jpg = stream.raw_data();
let dec = craft_image_codecs::decode(&raw_jpg).unwrap().to_rgba8();
[dec[0], dec[1], dec[2]]
} else {
let raw = stream.decoded().unwrap();
[raw[0], raw[1], raw[2]]
};
for ch in 0..3 {
assert!(
px[ch].abs_diff(expected_srgb[ch]) <= 4,
"{name} compress={compress_images} channel {ch}: got {px:?}, expected ~{:?} (unconverted {src_color:?})",
&expected_srgb[..3]
);
}
}
}
}
/// An RGB profile that parses as RGB but lacks a usable source transform (no matrix/TRC or AToB
/// tags) keeps display preview's best-effort fallback, but PDF/X-4 export must not tag its
/// unconverted samples as sRGB on JPEG, lossless PNG, or recompressed PNG.
#[test]
fn embedded_unconvertible_rgb_icc_is_not_tagged_as_srgb_in_pdfx4() {
let mut unconvertible_v43 = rgb_icc();
unconvertible_v43[8] = 4;
unconvertible_v43[9] = 0x30;
let parsed = craft_cms::Profile::parse(&unconvertible_v43).unwrap();
assert_eq!(parsed.color_space, craft_cms::ColorSpace::Rgb);
assert!(parsed.device_to_pcs(craft_cms::Intent::RelativeColorimetric).is_err());
let src_color = [60, 200, 60, 255];
let jpg = encode_with_icc(craft_image_codecs::Format::Jpeg, false, src_color, unconvertible_v43.clone());
let png_bytes = encode_with_icc(craft_image_codecs::Format::Png, false, src_color, unconvertible_v43);
// Display preview retains best-effort fallback when conversion is unavailable.
assert_eq!(designcraft_images::decode_rgba(&png_bytes).unwrap().get_pixel(0, 0).0, src_color);
assert!(designcraft_images::decode_rgba(&jpg).is_some());
for (name, bytes) in [("no-lut.jpg", jpg), ("no-lut.png", png_bytes)] {
let mut d = Document::new(&NewDocument::default());
place(&mut d, name, bytes, (4.0, 2.0), (72.0, 72.0));
for compress_images in [false, true] {
let opts = PdfOptions { standard: Standard::PdfX4, compress_images, ..Default::default() };
let r = export_pdf_with_report(&d, &Cache::new(), &opts).unwrap();
assert!(image_spaces(&r.bytes).is_empty(), "{name} compress={compress_images}: unconverted image was emitted");
assert!(r.warnings.iter().any(|w| w.contains(name)), "{name} compress={compress_images}: expected skip warning, got {:?}", r.warnings);
assert!(check_pdfx4(&r.bytes).is_empty(), "{name} compress={compress_images}: {:?}", check_pdfx4(&r.bytes));
}
}
}
/// Every image constructor asked for interpolation, which PDF/X-4 and PDF/A forbid: PDF/A