PhotoCraft: An open-source, photo editor written by scratch in pure Rust
PSD: save Indexed Color, Bitmap and Duotone documents in their own mode
Gert Pellin2a10524d5380
diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rsindex b80da66c3..309107a4c 100644--- a/crates/io/src/lib.rs+++ b/crates/io/src/lib.rs@@ -49,6 +49,7 @@ mod kra;pub mod linked;mod multichannel_map;mod ora;+mod palette_map;pub use ora::losses as ora_losses;pub mod pattern_map;mod pdn;diff --git a/crates/io/src/multichannel_map.rs b/crates/io/src/multichannel_map.rsindex db31e743e..365d55150 100644--- a/crates/io/src/multichannel_map.rs+++ b/crates/io/src/multichannel_map.rs@@ -119,7 +119,27 @@ pub(crate) fn document_to_psd(doc: &Document, force_psb: bool) -> (PsdFile, Vec<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, false)));}- resources.extend(crate::psd_export::path_resources(doc, &mut warnings));+ // Alpha identifiers: one u32 per channel, only while they still match the channels.+ let keep = |id: u16, data: &[u8]| id != ALPHA_IDENTIFIERS || data.len() == channels.len().saturating_mul(4);+ let color_mode_data = photocraft_psd::hdr::color_mode_data_for_depth(header.depth);+ let file = layerless_file(doc, header, image_data, color_mode_data, resources, keep, &mut warnings);+ (file, warnings)+}++/// A PSD without layers around `image_data`: `resources` (the mode's own) plus the paths, XMP,+/// EXIF and every other imported resource `keep` accepts (except the ones that only describe+/// layers and any already in `resources`), and the document-level tagged blocks. Shared by the+/// modes that have no layers in Photoshop: Multichannel, Indexed Color and Bitmap.+pub(crate) fn layerless_file(+ doc: &Document,+ header: Header,+ image_data: ImageData,+ color_mode_data: Vec<u8>,+ mut resources: Vec<ImageResource>,+ keep: impl Fn(u16, &[u8]) -> bool,+ warnings: &mut Vec<String>,+) -> PsdFile {+ resources.extend(crate::psd_export::path_resources(doc, warnings));// The XMP and EXIF resolution follow the ResolutionInfo resource, so no copy contradicts it.let ppi = Some((doc.resolution_dpi, doc.resolution_dpi)).filter(|d| d.0 > 0.0);if let Some(x) = &doc.metadata.xmp {@@ -132,11 +152,7 @@ pub(crate) fn document_to_psd(doc: &Document, force_psb: bool) -> (PsdFile, Vec<// ones that only describe layers and any already written above.let written: Vec<u16> = resources.iter().map(|r| r.id).collect();for (id, name, data) in &doc.metadata.psd_resources {- if LAYER_ONLY_RESOURCES.contains(id) || written.contains(id) || !crate::psd_export::keep_imported_resource(doc, *id, data) {- continue;- }- // Alpha identifiers: one u32 per channel, only while they still match the channels.- if *id == ALPHA_IDENTIFIERS && data.len() != channels.len().saturating_mul(4) {+ if LAYER_ONLY_RESOURCES.contains(id) || written.contains(id) || !crate::psd_export::keep_imported_resource(doc, *id, data) || !keep(*id, data) {continue;}let mut r = ImageResource::new(*id, data.to_vec());@@ -154,8 +170,7 @@ pub(crate) fn document_to_psd(doc: &Document, force_psb: bool) -> (PsdFile, Vec<.filter(|(_, key, _)| !matches!(key, b"Layr" | b"Lr16" | b"Lr32")).map(|(sig, key, data)| crate::psd_export::global_block(sig, key, &data)).collect();- let color_mode_data = photocraft_psd::hdr::color_mode_data_for_depth(header.depth);- let file = PsdFile {+ PsdFile {header,color_mode_data,resources,@@ -165,6 +180,5 @@ pub(crate) fn document_to_psd(doc: &Document, force_psb: bool) -> (PsdFile, Vec<global_blocks,layer_mask_trailing: Vec::new(),image_data,- };- (file, warnings)+ }}diff --git a/crates/io/src/palette_map.rs b/crates/io/src/palette_map.rsnew file mode 100644index 000000000..a279af0f4--- /dev/null+++ b/crates/io/src/palette_map.rs@@ -0,0 +1,107 @@+//! Indexed Color and Bitmap documents -> PSD colour modes 2 and 0.+//!+//! Neither mode has layers in Photoshop, so the file holds only the merged image (the document+//! flattened): for Indexed Color one plane of palette indices, with the Color Table as Color Mode+//! Data (768 bytes: 256 reds, 256 greens, 256 blues), its length in resource 1046 and the+//! transparent entry in resource 1047; for Bitmap one plane of 1 bit per pixel, 1 = black.++use photocraft_color::ColorMode;+use photocraft_doc::{ColorTable, Document};+use photocraft_psd::resources::{ImageResource, ResolutionInfo, ids};+use photocraft_psd::{ColorMode as PsdMode, Compression, Header, ImageData, PsdFile};++/// Indexed Color Table Count: the number of colours in the table (u16).+pub(crate) const COLOR_TABLE_COUNT: u16 = 1046;+/// Transparency Index: the colour table entry shown as transparent (u16).+pub(crate) const TRANSPARENCY_INDEX: u16 = 1047;+/// Channel resources (names, display info, alpha identifiers): these modes have no extra channels.+const CHANNEL_RESOURCES: [u16; 4] = [1006, 1045, 1053, crate::channel_map::DISPLAY_INFO];++/// The PSD for an Indexed Color document with a colour table of at most 256 entries, or a Bitmap+/// document; None for any other document (it is written like the others).+pub(crate) fn document_to_psd(doc: &Document, force_psb: bool) -> Option<(PsdFile, Vec<String>)> {+ let table = doc.color_table.as_ref().filter(|t| !t.colors.is_empty() && t.colors.len() <= 256);+ let (mode, plane, color_mode_data) = match doc.mode {+ ColorMode::Indexed => {+ let table = table?;+ (PsdMode::Indexed, indices(doc, table), palette(table))+ }+ ColorMode::Bitmap => (PsdMode::Bitmap, bits(doc), Vec::new()),+ _ => return None,+ };+ let mut warnings = Vec::new();+ if doc.layers.len() > 1 {+ warnings.push(format!("{:?} documents have no layers in Photoshop: written flattened", doc.mode));+ }+ let big = doc.size.width > 30_000 || doc.size.height > 30_000;+ let size_exceeds_limit = !force_psb && !big && crate::psd_export::psd_size_exceeds_limit(doc);+ let version = crate::psd_export::psd_version(doc, force_psb, size_exceeds_limit);+ let depth = if mode == PsdMode::Bitmap { 1 } else { 8 };+ let header = Header::new(version, doc.size.width, doc.size.height, 1, depth, mode);+ let image_data = ImageData::encode(Compression::Rle, &plane, &header)+ .or_else(|_| ImageData::encode(Compression::Raw, &plane, &header))+ .unwrap_or(ImageData { compression: Compression::Raw, data: plane });+ let mut resources = vec![+ ImageResource::new(ids::RESOLUTION_INFO, ResolutionInfo::from_dpi(f64::from(doc.resolution_dpi)).to_bytes()),+ ImageResource::new(ids::GLOBAL_ANGLE, (doc.global_light.angle.round() as i32).to_be_bytes().to_vec()),+ ImageResource::new(ids::GLOBAL_ALTITUDE, (doc.global_light.altitude.round() as i32).to_be_bytes().to_vec()),+ ImageResource::new(1032, crate::psd_export::guides_resource(doc)),+ ];+ if let (PsdMode::Indexed, Some(t)) = (mode, table) {+ resources.push(ImageResource::new(COLOR_TABLE_COUNT, (t.colors.len() as u16).to_be_bytes().to_vec()));+ if let Some(i) = t.transparent {+ resources.push(ImageResource::new(TRANSPARENCY_INDEX, u16::from(i).to_be_bytes().to_vec()));+ }+ }+ // An imported transparency index that no longer applies is not copied either.+ let keep = |id: u16, _: &[u8]| !CHANNEL_RESOURCES.contains(&id) && id != TRANSPARENCY_INDEX && id != COLOR_TABLE_COUNT;+ let file = crate::multichannel_map::layerless_file(doc, header, image_data, color_mode_data, resources, keep, &mut warnings);+ Some((file, warnings))+}++/// The Color Table as Color Mode Data: 256 reds, 256 greens, 256 blues (unused entries black).+fn palette(t: &ColorTable) -> Vec<u8> {+ let mut m = vec![0u8; 768];+ for (i, c) in t.colors.iter().take(256).enumerate() {+ m[i] = c[0];+ m[256 + i] = c[1];+ m[512 + i] = c[2];+ }+ m+}++/// The flattened document as palette indices (the nearest entry; the transparent one where the+/// document is less than half covered).+fn indices(doc: &Document, t: &ColorTable) -> Vec<u8> {+ let mut idx = Vec::with_capacity(doc.size.area() as usize);+ let _ = photocraft_compose::render_bands(doc, doc.bounds(), 0, |band| -> Result<(), ()> {+ idx.extend(band.px.iter().map(|p| match t.transparent {+ Some(i) if p[3] < 0.5 => i,+ _ => t.nearest([p[0], p[1], p[2]]) as u8,+ }));+ Ok(())+ });+ idx+}++/// The flattened document over white as 1-bit rows (padded to a byte), 1 = black: pixels darker+/// than middle grey.+fn bits(doc: &Document) -> Vec<u8> {+ let w = doc.size.width as usize;+ let row = w.div_ceil(8);+ let mut out = Vec::with_capacity(row * doc.size.height as usize);+ let _ = photocraft_compose::render_bands(doc, doc.bounds(), 0, |band| -> Result<(), ()> {+ for line in band.px.chunks(w.max(1)) {+ let mut bytes = vec![0u8; row];+ for (x, p) in line.iter().enumerate() {+ let grey = (p[0] + p[1] + p[2]) / 3.0 * p[3] + (1.0 - p[3]);+ if grey < 0.5 {+ bytes[x / 8] |= 0x80 >> (x % 8);+ }+ }+ out.extend(bytes);+ }+ Ok(())+ });+ out+}diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rsindex 4eada2422..9b5878af7 100644--- a/crates/io/src/psd_export.rs+++ b/crates/io/src/psd_export.rs@@ -1428,7 +1428,17 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, cif doc.mode == ColorMode::Multichannel {return crate::multichannel_map::document_to_psd(doc, opts.force_psb);}+ if let Some(file) = crate::palette_map::document_to_psd(doc, opts.force_psb) {+ return file;+ }let fmt = doc.pixel_format();+ // A Duotone keeps the inks it was imported with (their Color Mode Data is undocumented and+ // kept verbatim) over its grey plate; Photoshop has no 32-bit Duotone.+ let duotone_inks = doc+ .duotone+ .as_ref()+ .and_then(|d| d.psd_raw.as_ref())+ .filter(|_| doc.mode == ColorMode::Duotone && fmt.mode == ColorMode::Grayscale && fmt.sample != SampleType::F32);let sample = fmt.sample;let cc = fmt.mode.color_channels();let big = doc.size.width > 30_000 || doc.size.height > 30_000;@@ -1458,7 +1468,7 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, c} else if size_exceeds_limit && !opts.force_psb {ex.warnings.push("estimated encoded size exceeds 2 GB; written as PSB".into());}- if fmt.mode != doc.mode {+ if fmt.mode != doc.mode && duotone_inks.is_none() {ex.warnings.push(format!("{:?} document written as {:?}", doc.mode, fmt.mode));}// Assign layer ids up front (stable across round trips): keep unique@@ -1568,7 +1578,8 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, cplanes.extend(deinterleave(&bytes, 1, sample, &[false]).remove(0));}let channels = (cc + usize::from(has_alpha) + extra.len()) as u16;- let header = Header::new(version, doc.size.width, doc.size.height, channels, psd_depth(sample), psd_mode(fmt.mode));+ let mode = if duotone_inks.is_some() { PsdMode::Duotone } else { psd_mode(fmt.mode) };+ let header = Header::new(version, doc.size.width, doc.size.height, channels, psd_depth(sample), mode);let mcomp = if sample == SampleType::F32 { Compression::Raw } else { opts.merged_compression };let image_data = ImageData::encode(mcomp, &planes, &header).or_else(|_| ImageData::encode(Compression::Raw, &planes, &header))@@ -1706,7 +1717,10 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, c}// 32-bit files carry Photoshop's HDR toning records as Color Mode Data; Photoshop will not// open a 32-bit file without them (#291).- let color_mode_data = photocraft_psd::hdr::color_mode_data_for_depth(header.depth);+ let color_mode_data = match duotone_inks {+ Some(raw) => raw.to_vec(),+ None => photocraft_psd::hdr::color_mode_data_for_depth(header.depth),+ };let file = PsdFile {header,color_mode_data,diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rsindex 1e77cdaa6..151730013 100644--- a/crates/io/src/psd_import.rs+++ b/crates/io/src/psd_import.rs@@ -828,8 +828,12 @@ pub fn psd_to_document_with(file: &PsdFile, ctl: &photocraft_raster::Interrupt)if h.color_mode == PsdMode::Indexed && file.color_mode_data.len() >= 768 {// Planar palette: 256 reds, 256 greens, 256 blues (the Color Table).let m = &file.color_mode_data;- let colors = (0..256).map(|i| [m[i], m[256 + i], m[512 + i]]).collect();- doc.color_table = Some(photocraft_doc::ColorTable { colors, transparent: None });+ // Resource 1046 says how many entries are used, 1047 which one is transparent.+ let u16_of = |id: u16| file.resource(id).and_then(|r| r.data.get(..2)).map(|b| u16::from_be_bytes([b[0], b[1]]));+ let count = u16_of(crate::palette_map::COLOR_TABLE_COUNT).map_or(256, usize::from).clamp(1, 256);+ let colors = (0..count).map(|i| [m[i], m[256 + i], m[512 + i]]).collect();+ let transparent = u16_of(crate::palette_map::TRANSPARENCY_INDEX).filter(|&i| usize::from(i) < count).map(|i| i as u8);+ doc.color_table = Some(photocraft_doc::ColorTable { colors, transparent });} else if h.color_mode == PsdMode::Duotone && !file.color_mode_data.is_empty() {// The duotone ink block is undocumented: keep it raw; the image shows as its gray plate.doc.duotone =diff --git a/crates/io/tests/psd_structure.rs b/crates/io/tests/psd_structure.rsindex e893adaf9..5e4f85a57 100644--- a/crates/io/tests/psd_structure.rs+++ b/crates/io/tests/psd_structure.rs@@ -177,6 +177,47 @@ fn fallback_modes_import_flattened() {}}+#[test]+fn palette_and_duotone_modes_are_written_in_their_own_mode() {+ // Indexed Color and Bitmap are written flat in their own mode (palette / 1 bit); a Duotone+ // keeps the ink data it was imported with over its grey plate. Same image, same mode data.+ for mode in [ColorMode::Indexed, ColorMode::Bitmap, ColorMode::Duotone] {+ let depth = testgen::mode_depths(mode)[0];+ let f = testgen::merged_only(Version::Psd, mode, depth, Compression::Rle, 9, 5);+ let (d, _) = psd_to_document(&f);+ let out = export(&d, "x.psd", &ExportOptions::default()).unwrap();+ assert!(out.warnings.iter().all(|w| !w.contains("written as")), "{mode:?}: {:?}", out.warnings);+ let back = PsdFile::from_bytes(&out.bytes).unwrap();+ assert_eq!((back.header.color_mode, back.header.depth, back.header.channels), (mode, f.header.depth, 1), "{mode:?}");+ assert_eq!(back.composite_rgba8().unwrap(), f.composite_rgba8().unwrap(), "{mode:?}");+ if mode != ColorMode::Bitmap {+ assert_eq!(back.color_mode_data, f.color_mode_data, "{mode:?}");+ }+ }+}++#[test]+fn indexed_psd_keeps_the_table_length_and_transparent_entry() {+ use photocraft_doc::ColorTable;+ let mut d = photocraft_doc::Document::with_background(+ "i",+ photocraft_doc::Size::new(4, 2),+ photocraft_color::ColorMode::Rgb,+ photocraft_color::SampleType::U8,+ photocraft_color::Color::rgba(1.0, 0.0, 0.0, 1.0),+ );+ d.mode = photocraft_color::ColorMode::Indexed;+ d.color_table = Some(ColorTable { colors: vec![[0, 0, 0], [255, 0, 0], [0, 0, 255]], transparent: Some(2) });+ let out = export(&d, "x.psd", &ExportOptions::default()).unwrap();+ let f = PsdFile::from_bytes(&out.bytes).unwrap();+ assert_eq!(f.header.color_mode, ColorMode::Indexed);+ assert_eq!(f.resource(1046).map(|r| r.data.clone()), Some(vec![0, 3]));+ assert_eq!(f.resource(1047).map(|r| r.data.clone()), Some(vec![0, 2]));+ assert_eq!(f.decode_merged().unwrap(), vec![1; 8], "every pixel is entry 1 (red)");+ let (back, _) = psd_to_document(&f);+ assert_eq!(back.color_table, d.color_table);+}+#[test]fn multichannel_imports_ink_channels() {for depth in testgen::mode_depths(ColorMode::Multichannel) {