Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

PSD: alpha channel resources count the merged transparency, 13-byte DisplayInfo (#3577)

MrCloudy278c611007be0
diff --git a/crates/io/src/channel_map.rs b/crates/io/src/channel_map.rs
index f8dada8b0..a23775900 100644
--- a/crates/io/src/channel_map.rs
+++ b/crates/io/src/channel_map.rs
@@ -19,9 +19,16 @@ const SPACE_CMYK: u16 = 2;
const SPACE_LAB: u16 = 7;
const SPACE_GRAY: u16 = 8;
-/// Resource 1077 for `channels` (in file order).
-pub(crate) fn display_info(channels: &[&AlphaChannel]) -> Vec<u8> {
+/// Resource 1077 for `channels` (in file order): a version, then 13 bytes per channel (colour
+/// space, four components, opacity, kind). Every corpus file, Photoshop's included, uses 13;
+/// 14-byte records (the older 1007 layout) shift every channel after the first.
+/// `transparency`: the merged image's transparency channel comes first and gets a record too.
+pub(crate) fn display_info(channels: &[&AlphaChannel], transparency: bool) -> Vec<u8> {
let mut out = 1u32.to_be_bytes().to_vec();
+ if transparency {
+ // As Photoshop writes it: red, 100 %, masked areas.
+ out.extend_from_slice(&[0, 0, 0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 100, 1]);
+ }
for c in channels {
let (color, opacity, kind) = match c.spot {
Some((ink, solidity)) => (ink, solidity, 2u8),
@@ -34,15 +41,16 @@ pub(crate) fn display_info(channels: &[&AlphaChannel]) -> Vec<u8> {
}
out.extend_from_slice(&((opacity.clamp(0.0, 1.0) * 100.0).round() as u16).to_be_bytes());
out.push(kind);
- out.push(0);
}
out
}
-/// Applies a DisplayInfo resource (`versioned` = 1077) to the imported channels in order.
-pub(crate) fn apply_display_info(data: &[u8], versioned: bool, channels: &mut [AlphaChannel]) {
- let body = if versioned { data.get(4..).unwrap_or(&[]) } else { data };
- for (c, rec) in channels.iter_mut().zip(body.as_chunks::<14>().0) {
+/// Applies a DisplayInfo resource (`versioned` = 1077: 13-byte records after a version; else the
+/// older 1007 with 14-byte records) to the imported channels in order, after skipping `skip`
+/// records (the merged transparency channel's).
+pub(crate) fn apply_display_info(data: &[u8], versioned: bool, skip: usize, channels: &mut [AlphaChannel]) {
+ let (body, size) = if versioned { (data.get(4..).unwrap_or(&[]), 13) } else { (data, 14) };
+ for (c, rec) in channels.iter_mut().zip(body.chunks_exact(size).skip(skip)) {
let u = |i: usize| u16::from_be_bytes([rec[i], rec[i + 1]]);
let comps = [u(2), u(4), u(6), u(8)];
let color = decode_color(u(0), comps);
@@ -97,17 +105,25 @@ mod tests {
a.indicates = ColorIndicates::SelectedAreas;
let mut s = AlphaChannel::new("S", Surface::new(PixelFormat::GRAY8));
s.spot = Some((Color::rgb(1.0, 0.0, 1.0), 0.8));
- let bytes = display_info(&[&a, &s]);
- assert_eq!(bytes.len(), 4 + 28);
+ let bytes = display_info(&[&a, &s], false);
+ // 13 bytes per channel, as every corpus file (Photoshop's included) lays out 1077.
+ assert_eq!(bytes.len(), 4 + 2 * 13);
let mut back = vec![AlphaChannel::new("A", Surface::new(PixelFormat::GRAY8)), AlphaChannel::new("S", Surface::new(PixelFormat::GRAY8))];
- apply_display_info(&bytes, true, &mut back);
+ apply_display_info(&bytes, true, 0, &mut back);
assert_eq!(back[0].color, a.color);
assert!((back[0].opacity - 0.3).abs() < 1e-6);
assert_eq!(back[0].indicates, ColorIndicates::SelectedAreas);
assert_eq!(back[1].spot, s.spot);
+ // With the merged transparency's record first, the channels still get their own.
+ let with_t = display_info(&[&a, &s], true);
+ assert_eq!(with_t.len(), 4 + 3 * 13);
+ let mut back = vec![AlphaChannel::new("A", Surface::new(PixelFormat::GRAY8)), AlphaChannel::new("S", Surface::new(PixelFormat::GRAY8))];
+ apply_display_info(&with_t, true, 1, &mut back);
+ assert_eq!(back[0].indicates, ColorIndicates::SelectedAreas);
+ assert_eq!(back[1].spot, s.spot);
// Truncated data is ignored rather than misread.
let mut c = vec![AlphaChannel::new("x", Surface::new(PixelFormat::GRAY8))];
- apply_display_info(&bytes[..10], true, &mut c);
+ apply_display_info(&bytes[..10], true, 0, &mut c);
assert_eq!(c[0].opacity, 0.5);
}
diff --git a/crates/io/src/multichannel_map.rs b/crates/io/src/multichannel_map.rs
index 40b6884be..d20a70efc 100644
--- a/crates/io/src/multichannel_map.rs
+++ b/crates/io/src/multichannel_map.rs
@@ -48,9 +48,9 @@ pub(crate) fn import(file: &PsdFile, all: &[u8], doc: &mut Document, names: &[St
doc.channels.push(AlphaChannel { spot: Some((Color::BLACK, 0.0)), ..AlphaChannel::new(name, s) });
}
if let Some(r) = file.resource(crate::channel_map::DISPLAY_INFO) {
- crate::channel_map::apply_display_info(&r.data, true, &mut doc.channels);
+ crate::channel_map::apply_display_info(&r.data, true, 0, &mut doc.channels);
} else if let Some(r) = file.resource(crate::channel_map::DISPLAY_INFO_OLD) {
- crate::channel_map::apply_display_info(&r.data, false, &mut doc.channels);
+ crate::channel_map::apply_display_info(&r.data, false, 0, &mut doc.channels);
}
}
@@ -102,7 +102,7 @@ pub(crate) fn document_to_psd(doc: &Document, force_psb: bool) -> (PsdFile, Vec<
let names: Vec<&str> = channels.iter().map(|c| c.name.as_str()).collect();
resources.push(ImageResource::new(1006, crate::psd_export::pascal_names_resource(&names)));
resources.push(ImageResource::new(1045, crate::psd_export::unicode_names_resource(&names)));
- resources.push(ImageResource::new(crate::channel_map::DISPLAY_INFO, crate::channel_map::display_info(&channels)));
+ resources.push(ImageResource::new(crate::channel_map::DISPLAY_INFO, crate::channel_map::display_info(&channels, false)));
}
if let Some(x) = &doc.metadata.xmp {
resources.push(ImageResource::new(ids::XMP, x.as_bytes().to_vec()));
diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs
index 771ebcb78..5fdf83742 100644
--- a/crates/io/src/psd_export.rs
+++ b/crates/io/src/psd_export.rs
@@ -1435,10 +1435,12 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, c
resources.push(ImageResource::new(1032, guides_resource(doc)));
}
if !extra.is_empty() {
- let names: Vec<&str> = extra.iter().map(|a| a.name.as_str()).collect();
+ // One entry per extra channel, the merged transparency included (as in every file
+ // Photoshop opens; one short, Photoshop refuses the file with "unexpected end-of-file").
+ let names: Vec<&str> = has_alpha.then_some("Transparency").into_iter().chain(extra.iter().map(|a| a.name.as_str())).collect();
resources.push(ImageResource::new(1006, pascal_names_resource(&names)));
resources.push(ImageResource::new(1045, unicode_names_resource(&names)));
- resources.push(ImageResource::new(crate::channel_map::DISPLAY_INFO, crate::channel_map::display_info(&extra)));
+ resources.push(ImageResource::new(crate::channel_map::DISPLAY_INFO, crate::channel_map::display_info(&extra, has_alpha)));
}
if let Some(id) = quick_mask_id {
let mut data = id.to_be_bytes().to_vec();
@@ -1717,4 +1719,35 @@ mod tests {
assert_eq!(psd_version(&small, false, small_size_exceeds_limit), Version::Psd);
assert_eq!(psd_version(&small, true, small_size_exceeds_limit), Version::Psb);
}
+
+ /// A layered document with transparency in the merged image and an alpha channel: the name
+ /// and DisplayInfo resources hold one entry per extra channel, the merged transparency first,
+ /// as in every file Photoshop opens (one short, Photoshop 27.11 refused the file with "Could
+ /// not import the clipboard because an unexpected end-of-file was encountered"). The alpha
+ /// channel keeps its own name and options on the way back.
+ #[test]
+ fn alpha_names_count_the_merged_transparency() {
+ let mut doc = document(8, 6);
+ let mut layer = Layer::raster("Layer 1", doc.pixel_format());
+ layer.surface_mut().unwrap().write_pixel(1, 1, &[1.0, 0.0, 0.0, 1.0]);
+ doc.layers.push(layer);
+ let mut a = photocraft_doc::AlphaChannel::new("Alpha 1", photocraft_raster::Surface::new(PixelFormat::GRAY8));
+ a.opacity = 0.5;
+ doc.channels.push(a);
+ let file = document_to_psd(&doc);
+ let header_extra = usize::from(file.header.channels) - 3;
+ let names = |id| file.resources.iter().find(|r| r.id == id).map(|r| r.data.clone()).unwrap();
+ let pascal = names(1006);
+ let (mut count, mut i) = (0, 0);
+ while i < pascal.len() {
+ count += 1;
+ i += 1 + usize::from(pascal[i]);
+ }
+ assert_eq!((header_extra, count), (2, 2), "transparency + Alpha 1");
+ assert_eq!(names(crate::channel_map::DISPLAY_INFO).len(), 4 + 2 * 13);
+ let back = crate::import("a.psd", &file.to_bytes().unwrap()).unwrap().document;
+ assert_eq!(back.channels.len(), 1);
+ assert_eq!(back.channels[0].name, "Alpha 1");
+ assert!((back.channels[0].opacity - 0.5).abs() < 1e-6);
+ }
}
diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs
index da483c04d..24beaa904 100644
--- a/crates/io/src/psd_import.rs
+++ b/crates/io/src/psd_import.rs
@@ -808,6 +808,9 @@ pub fn psd_to_document_with(file: &PsdFile, ctl: &photocraft_raster::Interrupt)
let first = cc + usize::from(file.merged_has_alpha());
let plane = h.row_bytes() * hh;
let names = file.resource(1045).map(|r| unicode_names(&r.data)).unwrap_or_default();
+ // Photoshop lists every extra channel, the merged transparency first when there is one.
+ let skip = usize::from(file.merged_has_alpha() && names.len() == usize::from(h.channels).saturating_sub(cc));
+ let names = names.get(skip..).unwrap_or_default();
for (k, idx) in (first..usize::from(h.channels)).enumerate() {
let Some(p) = all.get(idx * plane..(idx + 1) * plane) else { break };
let mut s = Surface::new(cx.mask_fmt);
@@ -818,9 +821,9 @@ pub fn psd_to_document_with(file: &PsdFile, ctl: &photocraft_raster::Interrupt)
}
// Channel options (overlay colour, opacity, colour indicates) and spot inks.
if let Some(r) = file.resource(crate::channel_map::DISPLAY_INFO) {
- crate::channel_map::apply_display_info(&r.data, true, &mut doc.channels);
+ crate::channel_map::apply_display_info(&r.data, true, skip, &mut doc.channels);
} else if let Some(r) = file.resource(crate::channel_map::DISPLAY_INFO_OLD) {
- crate::channel_map::apply_display_info(&r.data, false, &mut doc.channels);
+ crate::channel_map::apply_display_info(&r.data, false, skip, &mut doc.channels);
}
// Saved in Quick Mask mode: that channel becomes the document's Quick Mask again.
if let Some(r) = file.resource(crate::channel_map::QUICK_MASK_INFO)