Skip to content

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

PSD export: write empty layer and mask channels as raw (#1290)

DWAA1660c833294e3412
diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs
index d9f9cc09e..f8f033733 100644
--- a/crates/io/src/psd_export.rs
+++ b/crates/io/src/psd_export.rs
@@ -244,7 +244,11 @@ impl Ex {
fn encode(&self, id: i16, plane: &[u8], w: usize, h: usize) -> ChannelData {
let depth = psd_depth(self.fmt.sample);
- ChannelData::encode(id, self.compression(), plane, w, h, depth, self.version)
+ // Photoshop writes empty layer/mask channels as just the raw compression code.
+ // A ZIP stream for a zero-sized channel makes readers try to decompress an
+ // invalid image extent (notably psd-tools for 32-bit adjustment layers).
+ let compression = if w == 0 || h == 0 { Compression::Raw } else { self.compression() };
+ ChannelData::encode(id, compression, plane, w, h, depth, self.version)
.or_else(|_| ChannelData::encode(id, Compression::Raw, plane, w, h, depth, self.version))
.unwrap_or(ChannelData { id, compression: Some(Compression::Raw), data: plane.to_vec() })
}
diff --git a/crates/io/tests/psd_empty_channels.rs b/crates/io/tests/psd_empty_channels.rs
new file mode 100644
index 000000000..285f03cfc
--- /dev/null
+++ b/crates/io/tests/psd_empty_channels.rs
@@ -0,0 +1,44 @@
+mod common;
+use common::Features;
+use photocraft_color::{ColorMode, SampleType};
+use photocraft_io::{ExportOptions, export};
+use photocraft_psd::{Compression, PsdFile};
+
+#[test]
+fn empty_layer_and_mask_channels_use_raw_without_a_payload() {
+ for mode in [ColorMode::Rgb, ColorMode::Grayscale] {
+ for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ for ext in ["out.psd", "out.psb"] {
+ let mut doc = common::gen_doc(mode, depth, Features::ALL);
+ let mut masked = common::raster("Uniform mask", doc.pixel_format(), photocraft_geom::Rect::new(0, 0, 3, 3), 1, true);
+ masked.mask = Some(photocraft_doc::LayerMask {
+ surface: photocraft_raster::Surface::new(photocraft_color::PixelFormat::new(ColorMode::Grayscale, depth, false)),
+ enabled: true,
+ linked: true,
+ density: 1.0,
+ feather: 0.0,
+ });
+ doc.layers.push(masked);
+ let bytes = export(&doc, ext, &ExportOptions::default()).unwrap().bytes;
+ let file = PsdFile::from_bytes(&bytes).unwrap();
+ let mut empty = 0;
+ let mut empty_masks = 0;
+ for layer in file.layers() {
+ for channel in &layer.channels {
+ let rect = layer.channel_rect(channel.id);
+ if rect.width() == 0 || rect.height() == 0 {
+ empty += 1;
+ if channel.id == -2 {
+ empty_masks += 1;
+ }
+ assert_eq!(channel.compression, Some(Compression::Raw), "{mode:?} {depth:?} {ext}: {} channel {}", layer.name(), channel.id);
+ assert!(channel.data.is_empty());
+ }
+ }
+ }
+ assert!(empty > 0);
+ assert!(empty_masks > 0);
+ }
+ }
+ }
+}