mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-26 23:58:03 +00:00
PSD import: File › Open converts a PSD file's layers to objects
Opening a .psd or .psb used to give one merged image. document.open now reads the layer records and builds the document from them. The PSD import options page (https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) says the option that converts layers to objects keeps as much of the layer structure as it can, merges the layers of a clipping mask into one layer and discards hidden layers that require merging, and that Import Hidden Layers brings hidden layers in. document.open does the same, with hiddenLayers: true for the hidden layers; layers: false keeps the merged image. VectorCraft's own rules: - Each layer becomes a layer holding its pixels as an image, with its name, visibility, opacity and blend mode. A group becomes a layer of sublayers; a Pass Through group is not isolated. - Clipped layers show where the layer below has pixels. That layer's fill opacity fades only its own pixels. Layers clipped to an adjustment layer, or to a fill that stores no pixels and isn't drawn, show over the whole canvas. - A layer mask becomes the layer's opacity mask, its default color and invert flag applied; a disabled mask is kept, switched off. - Fill opacity multiplies the layer's opacity. - Layers and groups in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, whether or not they hold transparent pixels; Color Dodge, Color Burn and Difference keep their mode. A merged Dissolve layer's pixels are opaque or transparent, in a pattern of each layer's own. - A solid color fill layer that stores no pixels and has no vector mask comes in as its color (RGB, CMYK, Grayscale, Lab or HSB). - A layer name stored only as a Pascal string, without its Unicode name, is read as Mac Roman. - Adjustment layers, fill layers that aren't drawn, layer effects that are switched on, knockouts and vector masks are not applied; the warnings count them. - A merge whose canvases need more memory than allowed leaves the layer alone, in the Normal mode or unclipped, with a warning. This changes what opening a layered PSD does. Batch Trace Folder passes layers: false, so a PSD is still traced as its merged image. A file whose layers can't be read, or whose layers and merges need more memory than allowed, opens as the merged image with a warning. Lengths, counts, nesting, decoded pixels and the canvases merges make are bounded. Zipped 32-bit data with prediction is now read, in layers and in the merged image. import_fuzz gains a case that mutates the PSD and PSB samples and opens them with their layers. The PSD reader's new error messages have rows in every catalog. Docs: docs/mcp.md, docs/target-app-parity.md, docs/file-format-parity.md, README.
This commit is contained in:
@@ -113,7 +113,8 @@ pub(super) fn batch_trace_folder(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for path in &files {
|
||||
let opened_before = s.documents().len();
|
||||
let one = |s: &mut Session| -> Result<String> {
|
||||
s.execute("document.open", &json!({ "path": path }))?;
|
||||
// A PSD or PSB is traced as its merged image, not as the first of its layers.
|
||||
s.execute("document.open", &json!({ "path": path, "layers": false }))?;
|
||||
s.execute("select.all", &json!({}))?;
|
||||
s.execute(trace, &json!({ "preset": preset }))?;
|
||||
let stem = fileio::file_stem(path);
|
||||
|
||||
@@ -333,6 +333,34 @@ fn batch_trace_folder_traces_and_saves_each_image() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A layered PSD is traced as its merged image: a white layer under a black square gives the
|
||||
/// square's shape, not a trace of the white layer alone.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn batch_trace_folder_traces_a_layered_psd_as_its_merged_image() {
|
||||
const C: &str = "addon.document.batchTraceFolder";
|
||||
let dir = folder("batch-trace-psd");
|
||||
let (src, out) = (dir.join("in"), dir.join("out"));
|
||||
std::fs::create_dir_all(&src).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 24, "height": 24})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 24, "height": 24})).unwrap();
|
||||
s.execute("layer.new", &json!({"name": "Square"})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 6, "y": 6, "width": 12, "height": 12})).unwrap();
|
||||
let psd = s.execute("document.export", &json!({"format": "psd"})).unwrap();
|
||||
std::fs::write(src.join("two.psd"), vectorcraft_format::base64_decode(psd["dataBase64"].as_str().unwrap()).unwrap()).unwrap();
|
||||
let r =
|
||||
s.execute(C, &json!({"folder": src, "destinationFolder": out, "format": "svg", "preset": "Black and White Logo", "expand": true})).unwrap();
|
||||
assert_eq!(r["traced"].as_array().unwrap().len(), 1, "{r}");
|
||||
let svg = std::fs::read_to_string(out.join("two.svg")).unwrap();
|
||||
assert!(svg.contains("fill=\"#000000\""), "the black square is traced: {svg}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Batch Trace Folder rejects optional values with the wrong type before opening images.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
|
||||
@@ -50,6 +50,7 @@ mod pdfimport;
|
||||
pub mod pngtext;
|
||||
pub mod ppi;
|
||||
pub mod progress;
|
||||
mod psdlayers;
|
||||
pub mod psdread;
|
||||
mod pxrread;
|
||||
mod save;
|
||||
@@ -218,6 +219,8 @@ mod tests_pdfx;
|
||||
#[cfg(test)]
|
||||
mod tests_psd;
|
||||
#[cfg(test)]
|
||||
mod tests_psdlayers;
|
||||
#[cfg(test)]
|
||||
mod tests_psdread;
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -493,7 +493,8 @@ pub const FORMATS: &[Format] = &[
|
||||
// Affinity Photo's `.afphoto` opens by its content but isn't listed: Finder shouldn't offer a
|
||||
// vector app for a raster editor's documents.
|
||||
reader("affinity", "Affinity", &["af", "afdesign", "afpub"], "application/x-affinity", false),
|
||||
// Photoshop's large document format: read like a PSD (its merged image), never written.
|
||||
// The large document form of PSD: read like a PSD (its layers, or its merged image), never
|
||||
// written.
|
||||
reader("psb", "PSB", &["psb"], "image/x-psb", true),
|
||||
// PostScript programs, read as EPS files are; Print to PostScript writes them, exports don't.
|
||||
reader("ps", "PostScript", &["ps"], "application/postscript", false),
|
||||
|
||||
@@ -492,6 +492,16 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
preview_only = i.preview_only;
|
||||
(i.doc, i.warnings, false)
|
||||
}
|
||||
// A PSD or PSB file's layers become layers (`layers`, default on); without layers, or with
|
||||
// `layers: false`, its merged image opens. Layers that can't be read leave the merged image.
|
||||
"psd" | "psb" if opts.layers => {
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
match super::psdlayers::import(bytes, opts.hidden_layers, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)) {
|
||||
Ok(Some((doc, warnings))) => (doc, warnings, false),
|
||||
Ok(None) => (raster_doc(&title, bytes)?, vec![], false),
|
||||
Err(e) => (raster_doc(&title, bytes)?, vec![format!("the layers can't be read ({e}): the file opened as its merged image")], false),
|
||||
}
|
||||
}
|
||||
_ if format.raster => (raster_doc(&title, bytes)?, vec![], false),
|
||||
_ => return Err(err(format!("{} files can't be opened yet", format.label))),
|
||||
};
|
||||
|
||||
@@ -28,8 +28,10 @@ pub struct LoadOptions {
|
||||
/// What a PDF's text becomes.
|
||||
pub text_as: TextAs,
|
||||
/// A PDF's optional content groups become layers (else one layer per page, without the art
|
||||
/// that is off).
|
||||
/// that is off), and a PSD or PSB file's layers become layers (else its merged image opens).
|
||||
pub layers: bool,
|
||||
/// A PSD or PSB file's hidden layers come in, hidden (`hiddenLayers`; else they are left out).
|
||||
pub hidden_layers: bool,
|
||||
/// How a DXF drawing comes in (the `dxf` param, see [`super::dxfimport`]).
|
||||
pub dxf: vectorcraft_cad::ImportOptions,
|
||||
/// An Illustrator EPS or `.ai` that carries the editing copy of its art opens from it (its
|
||||
@@ -57,6 +59,7 @@ impl Default for LoadOptions {
|
||||
grays: Grays::default(),
|
||||
text_as: TextAs::default(),
|
||||
layers: true,
|
||||
hidden_layers: false,
|
||||
dxf: Default::default(),
|
||||
editing_data: true,
|
||||
trust_editing_data: false,
|
||||
@@ -69,7 +72,8 @@ impl Default for LoadOptions {
|
||||
impl LoadOptions {
|
||||
/// From command params: `pages` (`"2-3, 5"`, a page number or `"all"`), `page` (one page, when
|
||||
/// `pages` isn't given), `cropTo` (or `crop`), `password`, `colorMode` (`rgb` | `cmyk`) with `grays`,
|
||||
/// `textAs` (`text` | `outlines`), `layers` (true | false), `editingData` (true | false | `always`),
|
||||
/// `textAs` (`text` | `outlines`), `layers` (true | false), `hiddenLayers` (true | false),
|
||||
/// `editingData` (true | false | `always`),
|
||||
/// `legacyNameEncoding` (one of [`vectorcraft_eps::NameEncoding::LABELS`]) and `dxf` (the DXF
|
||||
/// import options).
|
||||
pub fn from_params(cmd: &str, p: &Value) -> Result<Self> {
|
||||
@@ -95,6 +99,10 @@ impl LoadOptions {
|
||||
None => true,
|
||||
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "layers must be true or false"))?,
|
||||
};
|
||||
let hidden_layers = match p.get("hiddenLayers").filter(|v| !v.is_null()) {
|
||||
None => false,
|
||||
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "hiddenLayers must be true or false"))?,
|
||||
};
|
||||
let (editing_data, trust_editing_data) = match p.get("editingData").filter(|v| !v.is_null()) {
|
||||
None => (true, false),
|
||||
Some(Value::String(s)) if s.eq_ignore_ascii_case("always") => (true, true),
|
||||
@@ -108,7 +116,21 @@ impl LoadOptions {
|
||||
.ok_or_else(|| bad(cmd, format!("legacyNameEncoding must be one of {}", vectorcraft_eps::NameEncoding::LABELS.join(", "))))?,
|
||||
};
|
||||
let dxf = super::dxfimport::options(cmd, p.get("dxf"))?;
|
||||
Ok(Self { pages, crop, password, color_mode, grays, text_as, layers, dxf, editing_data, trust_editing_data, legacy_names, native: true })
|
||||
Ok(Self {
|
||||
pages,
|
||||
crop,
|
||||
password,
|
||||
color_mode,
|
||||
grays,
|
||||
text_as,
|
||||
layers,
|
||||
hidden_layers,
|
||||
dxf,
|
||||
editing_data,
|
||||
trust_editing_data,
|
||||
legacy_names,
|
||||
native: true,
|
||||
})
|
||||
}
|
||||
|
||||
/// Does the document read only part of the file, or read it differently (a page range, another
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,8 @@
|
||||
//! Reading Photoshop documents (PSD, and PSB, the large document format) for File › Open and
|
||||
//! File › Place (#918): the merged image, the flattened picture every PSD carries after its layers,
|
||||
//! as a linked PSD shows. Written from Adobe's public "Photoshop File Formats Specification"
|
||||
//! (<https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/>). Layers aren't read.
|
||||
//! (<https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/>). File › Open reads the
|
||||
//! layers with [`super::psdlayers`], which shares this reader.
|
||||
//!
|
||||
//! Every mode Photoshop saves a merged image in is read: Bitmap, Grayscale, Duotone (as its
|
||||
//! grayscale data), Indexed, RGB, CMYK and Lab, at 1, 8, 16 and 32 bits per channel, stored raw,
|
||||
@@ -16,7 +17,7 @@ use vectorcraft_color::cms::{Lab, lab::lab_to_srgb};
|
||||
|
||||
/// Photoshop's colour modes (the header's numbers), as far as the merged image is concerned.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Mode {
|
||||
pub(super) enum Mode {
|
||||
Bitmap,
|
||||
Gray,
|
||||
Indexed,
|
||||
@@ -27,7 +28,7 @@ enum Mode {
|
||||
|
||||
impl Mode {
|
||||
/// The channels holding colour (an alpha channel may follow them).
|
||||
fn colors(self) -> usize {
|
||||
pub(super) fn colors(self) -> usize {
|
||||
match self {
|
||||
Mode::Bitmap | Mode::Gray | Mode::Indexed => 1,
|
||||
Mode::Rgb | Mode::Lab => 3,
|
||||
@@ -46,68 +47,68 @@ pub fn is_psb(bytes: &[u8]) -> bool {
|
||||
is_psd(bytes) && bytes.get(4..6) == Some(&[0, 2])
|
||||
}
|
||||
|
||||
const TRUNCATED: &str = "the PSD file is cut short";
|
||||
pub(super) const TRUNCATED: &str = "the PSD file is cut short";
|
||||
const DAMAGED: &str = "the PSD file's header is damaged";
|
||||
|
||||
/// Big-endian reads through `b`, each checked against its end.
|
||||
struct Reader<'a> {
|
||||
pub(super) struct Reader<'a> {
|
||||
b: &'a [u8],
|
||||
at: usize,
|
||||
}
|
||||
|
||||
impl<'a> Reader<'a> {
|
||||
fn new(b: &'a [u8]) -> Self {
|
||||
pub(super) fn new(b: &'a [u8]) -> Self {
|
||||
Self { b, at: 0 }
|
||||
}
|
||||
fn take(&mut self, n: usize) -> Result<&'a [u8], String> {
|
||||
pub(super) fn take(&mut self, n: usize) -> Result<&'a [u8], String> {
|
||||
let s = self.at.checked_add(n).and_then(|end| self.b.get(self.at..end)).ok_or(TRUNCATED)?;
|
||||
self.at += n;
|
||||
Ok(s)
|
||||
}
|
||||
fn array<const N: usize>(&mut self) -> Result<[u8; N], String> {
|
||||
pub(super) fn array<const N: usize>(&mut self) -> Result<[u8; N], String> {
|
||||
self.take(N)?.try_into().map_err(|_| TRUNCATED.to_string())
|
||||
}
|
||||
fn u8(&mut self) -> Result<u8, String> {
|
||||
pub(super) fn u8(&mut self) -> Result<u8, String> {
|
||||
self.array::<1>().map(|[v]| v)
|
||||
}
|
||||
fn u16(&mut self) -> Result<u16, String> {
|
||||
pub(super) fn u16(&mut self) -> Result<u16, String> {
|
||||
self.array().map(u16::from_be_bytes)
|
||||
}
|
||||
fn u32(&mut self) -> Result<u32, String> {
|
||||
pub(super) fn u32(&mut self) -> Result<u32, String> {
|
||||
self.array().map(u32::from_be_bytes)
|
||||
}
|
||||
/// A section length: 4 bytes in a PSD, 8 in a PSB.
|
||||
fn length(&mut self, psb: bool) -> Result<usize, String> {
|
||||
pub(super) fn length(&mut self, psb: bool) -> Result<usize, String> {
|
||||
let n = if psb { self.array().map(u64::from_be_bytes)? } else { u64::from(self.u32()?) };
|
||||
usize::try_from(n).map_err(|_| TRUNCATED.to_string())
|
||||
}
|
||||
/// A section: its length, then that many bytes.
|
||||
fn section(&mut self, psb: bool) -> Result<&'a [u8], String> {
|
||||
pub(super) fn section(&mut self, psb: bool) -> Result<&'a [u8], String> {
|
||||
let n = self.length(psb)?;
|
||||
self.take(n)
|
||||
}
|
||||
fn rest(&self) -> &'a [u8] {
|
||||
pub(super) fn rest(&self) -> &'a [u8] {
|
||||
self.b.get(self.at..).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The fixed-size header and the sections before the image data.
|
||||
struct Header<'a> {
|
||||
psb: bool,
|
||||
pub(super) struct Header<'a> {
|
||||
pub(super) psb: bool,
|
||||
channels: usize,
|
||||
width: u32,
|
||||
height: u32,
|
||||
depth: u16,
|
||||
mode: Mode,
|
||||
pub(super) width: u32,
|
||||
pub(super) height: u32,
|
||||
pub(super) depth: u16,
|
||||
pub(super) mode: Mode,
|
||||
/// Colour mode data: an indexed image's palette (256 reds, then greens, then blues).
|
||||
palette: &'a [u8],
|
||||
/// The image resources.
|
||||
resources: &'a [u8],
|
||||
/// The layer and mask information.
|
||||
layers: &'a [u8],
|
||||
pub(super) layers: &'a [u8],
|
||||
}
|
||||
|
||||
fn header<'a>(r: &mut Reader<'a>) -> Result<Header<'a>, String> {
|
||||
pub(super) fn header<'a>(r: &mut Reader<'a>) -> Result<Header<'a>, String> {
|
||||
if !is_psd(r.b) {
|
||||
return Err("not a PSD file".into());
|
||||
}
|
||||
@@ -183,41 +184,45 @@ pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> {
|
||||
/// count is negative: in the layer info, or for 16- and 32-bit documents (whose layer info is
|
||||
/// empty) in their `Lr16` / `Lr32` block.
|
||||
fn merged_alpha(layers: &[u8], psb: bool) -> bool {
|
||||
let count_negative = |info: &[u8]| info.get(..2).is_some_and(|c| i16::from_be_bytes([c[0], c[1]]) < 0);
|
||||
layer_info(layers, psb).is_some_and(|info| info.get(..2).is_some_and(|c| i16::from_be_bytes([c[0], c[1]]) < 0))
|
||||
}
|
||||
|
||||
/// Do tagged blocks with this key give an 8-byte length in a PSB?
|
||||
pub(super) fn long_key(key: &[u8; 4]) -> bool {
|
||||
matches!(key, b"Lr16" | b"Lr32" | b"Layr" | b"LMsk" | b"Mt16" | b"Mt32" | b"Mtrn" | b"Alph" | b"FMsk" | b"lnk2" | b"FEid" | b"FXid" | b"PxSD")
|
||||
}
|
||||
|
||||
/// The layer info: the layer count, the layer records and their channels. It is the first part of
|
||||
/// the layer and mask information, or for 16- and 32-bit documents (whose first part is empty) the
|
||||
/// `Lr16` / `Lr32` block after it. `None` when the file has neither.
|
||||
pub(super) fn layer_info(layers: &[u8], psb: bool) -> Option<&[u8]> {
|
||||
let mut r = Reader::new(layers);
|
||||
let Ok(info) = r.section(psb) else { return false };
|
||||
let info = r.section(psb).ok()?;
|
||||
if !info.is_empty() {
|
||||
return count_negative(info);
|
||||
return Some(info);
|
||||
}
|
||||
// The global layer mask info, then tagged blocks: signature, key, length (8 bytes for the
|
||||
// layer blocks of a PSB), data padded to 4 bytes.
|
||||
if r.section(false).is_err() {
|
||||
return false;
|
||||
}
|
||||
r.section(false).ok()?;
|
||||
while r.rest().len() >= 12 {
|
||||
let (Ok(_), Ok(key)) = (r.take(4), r.array::<4>()) else { return false };
|
||||
let layer_block = matches!(&key, b"Lr16" | b"Lr32" | b"Layr");
|
||||
let long = layer_block || matches!(&key, b"LMsk" | b"Mt16" | b"Mt32" | b"Mtrn" | b"Alph" | b"FMsk" | b"lnk2" | b"FEid" | b"FXid" | b"PxSD");
|
||||
let Ok(data) = r.section(psb && long) else {
|
||||
return false;
|
||||
};
|
||||
if layer_block {
|
||||
return count_negative(data);
|
||||
}
|
||||
if r.take((4 - data.len() % 4) % 4).is_err() {
|
||||
return false;
|
||||
r.take(4).ok()?;
|
||||
let key = r.array::<4>().ok()?;
|
||||
let data = r.section(psb && long_key(&key)).ok()?;
|
||||
if matches!(&key, b"Lr16" | b"Lr32" | b"Layr") {
|
||||
return Some(data);
|
||||
}
|
||||
r.take((4 - data.len() % 4) % 4).ok()?;
|
||||
}
|
||||
false
|
||||
None
|
||||
}
|
||||
|
||||
/// The most bytes one channel row may take (a PSB at 32 bits).
|
||||
fn row_bytes(width: usize, depth: u16) -> usize {
|
||||
pub(super) fn row_bytes(width: usize, depth: u16) -> usize {
|
||||
if depth == 1 { width.div_ceil(8) } else { width * usize::from(depth / 8) }
|
||||
}
|
||||
|
||||
/// Undo PackBits: `src` into `dst` (a row; a short or overlong run leaves the rest as it is).
|
||||
fn unpack_bits(mut src: &[u8], dst: &mut [u8]) {
|
||||
pub(super) fn unpack_bits(mut src: &[u8], dst: &mut [u8]) {
|
||||
let mut at = 0;
|
||||
while let Some((&n, rest)) = src.split_first() {
|
||||
src = rest;
|
||||
@@ -269,32 +274,77 @@ fn channel_data(data: &[u8], h: &Header<'_>, channels: usize, row: usize) -> Res
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
2 | 3 => {
|
||||
let mut out = Vec::new();
|
||||
flate2::read::ZlibDecoder::new(r.rest())
|
||||
.take(wanted as u64)
|
||||
.read_to_end(&mut out)
|
||||
.map_err(|e| format!("the PSD file's image data can't be read: {e}"))?;
|
||||
if out.len() < wanted {
|
||||
return Err(TRUNCATED.into());
|
||||
}
|
||||
if method == 3 {
|
||||
// Each row stores the difference from the sample before it.
|
||||
match h.depth {
|
||||
8 => out.chunks_exact_mut(row).for_each(|r| (1..r.len()).for_each(|i| r[i] = r[i].wrapping_add(r[i - 1]))),
|
||||
16 => out.chunks_exact_mut(row).for_each(|r| {
|
||||
let mut prev = 0u16;
|
||||
for s in r.as_chunks_mut::<2>().0 {
|
||||
prev = prev.wrapping_add(u16::from_be_bytes(*s));
|
||||
*s = prev.to_be_bytes();
|
||||
}
|
||||
}),
|
||||
_ => return Err("zipped 32-bit PSD image data with prediction can't be read".into()),
|
||||
2 | 3 => inflate(r.rest(), wanted, method == 3, h.depth, row),
|
||||
m => Err(format!("the PSD file's image data uses an unknown compression ({m})")),
|
||||
}
|
||||
}
|
||||
|
||||
/// `wanted` bytes of zipped image data, rows of `row` bytes; with `predicted`, each row stores the
|
||||
/// difference from the sample before it. In 32-bit data a row stores the first bytes of its samples,
|
||||
/// then their second bytes, and so on, and the differences run byte by byte along the whole row (as
|
||||
/// psd-tools, MIT, reads it: <https://github.com/psd-tools/psd-tools>, `compression/__init__.py`).
|
||||
fn inflate(src: &[u8], wanted: usize, predicted: bool, depth: u16, row: usize) -> Result<Vec<u8>, String> {
|
||||
let mut out = Vec::new();
|
||||
flate2::read::ZlibDecoder::new(src)
|
||||
.take(wanted as u64)
|
||||
.read_to_end(&mut out)
|
||||
.map_err(|e| format!("the PSD file's image data can't be read: {e}"))?;
|
||||
if out.len() < wanted {
|
||||
return Err(TRUNCATED.into());
|
||||
}
|
||||
if predicted && row > 0 {
|
||||
match depth {
|
||||
8 => out.chunks_exact_mut(row).for_each(|r| (1..r.len()).for_each(|i| r[i] = r[i].wrapping_add(r[i - 1]))),
|
||||
16 => out.chunks_exact_mut(row).for_each(|r| {
|
||||
let mut prev = 0u16;
|
||||
for s in r.as_chunks_mut::<2>().0 {
|
||||
prev = prev.wrapping_add(u16::from_be_bytes(*s));
|
||||
*s = prev.to_be_bytes();
|
||||
}
|
||||
}),
|
||||
32 => {
|
||||
let w = row / 4;
|
||||
let mut planes = vec![0u8; row];
|
||||
for r in out.chunks_exact_mut(row) {
|
||||
let mut prev = 0u8;
|
||||
for (dst, &b) in planes.iter_mut().zip(r.iter()) {
|
||||
prev = prev.wrapping_add(b);
|
||||
*dst = prev;
|
||||
}
|
||||
for (x, s) in r.as_chunks_mut::<4>().0.iter_mut().enumerate() {
|
||||
for (k, v) in s.iter_mut().enumerate() {
|
||||
*v = planes.get(k * w + x).copied().unwrap_or(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// 1-bit.
|
||||
_ => return Err("zipped 1-bit PSD image data with prediction can't be read".into()),
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// One channel of a layer: its compression method, then `rows` rows of `row` bytes (PackBits rows
|
||||
/// after their byte counts, 4 bytes each in a PSB).
|
||||
pub(super) fn layer_channel(data: &[u8], rows: usize, row: usize, psb: bool, depth: u16) -> Result<Vec<u8>, String> {
|
||||
let mut r = Reader::new(data);
|
||||
let method = r.u16()?;
|
||||
let wanted = rows.checked_mul(row).ok_or(TRUNCATED)?;
|
||||
match method {
|
||||
0 => r.take(wanted).map(<[u8]>::to_vec),
|
||||
1 => {
|
||||
let size = if psb { 4 } else { 2 };
|
||||
let counts = r.take(rows.checked_mul(size).ok_or(TRUNCATED)?)?;
|
||||
let mut out = vec![0; wanted];
|
||||
for (dst, n) in out.chunks_exact_mut(row.max(1)).zip(counts.chunks_exact(size)) {
|
||||
let n = n.iter().fold(0usize, |n, &b| n << 8 | usize::from(b));
|
||||
unpack_bits(r.take(n)?, dst);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
m => Err(format!("the PSD file's image data uses an unknown compression ({m})")),
|
||||
2 | 3 => inflate(r.rest(), wanted, method == 3, depth, row),
|
||||
m => Err(format!("the PSD file's layer data uses an unknown compression ({m})")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -304,7 +354,7 @@ fn srgb_encode(v: f32) -> f32 {
|
||||
}
|
||||
|
||||
/// Sample `x` of a channel row, 0..1.
|
||||
fn sample(row: &[u8], x: usize, depth: u16, linear: bool) -> f32 {
|
||||
pub(super) fn sample(row: &[u8], x: usize, depth: u16, linear: bool) -> f32 {
|
||||
match depth {
|
||||
1 => {
|
||||
// Bitmap: a set bit is black.
|
||||
@@ -321,10 +371,25 @@ fn sample(row: &[u8], x: usize, depth: u16, linear: bool) -> f32 {
|
||||
}
|
||||
}
|
||||
|
||||
fn byte(v: f32) -> u8 {
|
||||
pub(super) fn byte(v: f32) -> u8 {
|
||||
(v.clamp(0.0, 1.0) * 255.0).round() as u8
|
||||
}
|
||||
|
||||
/// The sRGB color of a pixel whose color channels `v` gives (0..1, as stored), in `h`'s mode.
|
||||
pub(super) fn to_rgb(h: &Header<'_>, v: impl Fn(usize) -> f32, cmyk: &impl Fn([f32; 4]) -> [f32; 3]) -> [f32; 3] {
|
||||
match h.mode {
|
||||
Mode::Bitmap | Mode::Gray => [v(0); 3],
|
||||
Mode::Indexed => {
|
||||
let i = usize::from(byte(v(0)));
|
||||
[0, 256, 512].map(|at| h.palette.get(at + i).map_or(0.0, |&c| f32::from(c) / 255.0))
|
||||
}
|
||||
Mode::Rgb => [v(0), v(1), v(2)],
|
||||
// Inks are stored as 1 − amount.
|
||||
Mode::Cmyk => cmyk([0, 1, 2, 3].map(|c| 1.0 - v(c))),
|
||||
Mode::Lab => lab_to_srgb(Lab { l: v(0) * 100.0, a: v(1) * 255.0 - 128.0, b: v(2) * 255.0 - 128.0 }),
|
||||
}
|
||||
}
|
||||
|
||||
/// A Photoshop document's merged image as straight RGBA. CMYK converts through `cmyk` (ink
|
||||
/// amounts 0..1 → sRGB). Fails, without allocating, when the image would need more than
|
||||
/// `max_alloc` bytes.
|
||||
@@ -348,17 +413,7 @@ pub fn decode(bytes: &[u8], max_alloc: u64, cmyk: impl Fn([f32; 4]) -> [f32; 3])
|
||||
let planes: Vec<&[u8]> = (0..channels).map(|c| data.get((c * rows + y) * row..(c * rows + y + 1) * row).unwrap_or_default()).collect();
|
||||
for (x, px) in line.enumerate() {
|
||||
let v = |c: usize| planes.get(c).map_or(0.0, |p| sample(p, x, h.depth, linear && c < colors));
|
||||
let rgb = match h.mode {
|
||||
Mode::Bitmap | Mode::Gray => [v(0); 3],
|
||||
Mode::Indexed => {
|
||||
let i = usize::from(byte(v(0)));
|
||||
[0, 256, 512].map(|at| h.palette.get(at + i).map_or(0.0, |&c| f32::from(c) / 255.0))
|
||||
}
|
||||
Mode::Rgb => [v(0), v(1), v(2)],
|
||||
// Inks are stored as 1 − amount.
|
||||
Mode::Cmyk => cmyk([0, 1, 2, 3].map(|c| 1.0 - v(c))),
|
||||
Mode::Lab => lab_to_srgb(Lab { l: v(0) * 100.0, a: v(1) * 255.0 - 128.0, b: v(2) * 255.0 - 128.0 }),
|
||||
};
|
||||
let rgb = to_rgb(&h, v, &cmyk);
|
||||
let a = if alpha { v(colors) } else { 1.0 };
|
||||
// The merged image is stored on white: take the white back out.
|
||||
let straight = |c: f32| if a <= 0.0 { 0.0 } else { (c - (1.0 - a)) / a };
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -141,6 +141,31 @@ fn packbits_zip_and_psb_files_read() {
|
||||
zip.extend(z.finish().unwrap());
|
||||
let px = pixels(&psd(1, 1, (3, 1), 16, 1, &[], &[], &[], &zip));
|
||||
assert_eq!(px.iter().map(|p| p[0]).collect::<Vec<_>>(), [16, 32, 48]);
|
||||
// Zipped with prediction, 32 bits: the row's first bytes, then its second bytes and so on,
|
||||
// each byte stored as the difference from the byte before it.
|
||||
let samples = [0.0f32, 1.0, 0.0].map(f32::to_be_bytes);
|
||||
let planes: Vec<u8> = (0..4).flat_map(|k| samples.iter().map(move |s| s[k])).collect();
|
||||
let deltas: Vec<u8> = planes.iter().scan(0u8, |prev, &b| Some(b.wrapping_sub(std::mem::replace(prev, b)))).collect();
|
||||
let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
|
||||
std::io::Write::write_all(&mut z, &deltas).unwrap();
|
||||
let mut zip = vec![0, 3];
|
||||
zip.extend(z.finish().unwrap());
|
||||
let px = pixels(&psd(1, 1, (3, 1), 32, 1, &[], &[], &[], &zip));
|
||||
assert_eq!(px.iter().map(|p| p[0]).collect::<Vec<_>>(), [0, 255, 0]);
|
||||
// The same layout as another implementation writes it: psd-tools 1.26.1 (MIT,
|
||||
// <https://github.com/psd-tools/psd-tools>), `compression.compress(data,
|
||||
// Compression.ZIP_WITH_PREDICTION, 3, 2, 32)` of the samples 0, 1, 0.25 and 0.5, 0.125, 1,
|
||||
// reads as the same samples stored raw.
|
||||
let theirs = [
|
||||
0x78, 0x9c, 0x63, 0xb0, 0xff, 0x7f, 0xa8, 0x81, 0xa1, 0x81, 0x01, 0x04, 0xec, 0xff, 0x33, 0x1e, 0x64, 0x68, 0x80, 0xb0, 0x01, 0x59, 0xd1,
|
||||
0x06, 0x01,
|
||||
];
|
||||
let mut zip = vec![0, 3];
|
||||
zip.extend(theirs);
|
||||
let samples: Vec<u8> = [0.0f32, 1.0, 0.25, 0.5, 0.125, 1.0].iter().flat_map(|v| v.to_be_bytes()).collect();
|
||||
let stored = pixels(&psd(1, 1, (3, 2), 32, 1, &[], &[], &[], &raw(&[&samples])));
|
||||
assert_eq!(pixels(&psd(1, 1, (3, 2), 32, 1, &[], &[], &[], &zip)), stored);
|
||||
assert_eq!(stored.iter().map(|p| p[0]).collect::<Vec<_>>()[..2], [0, 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -108,7 +108,7 @@ pub(in crate::cmd) fn windows_1252(b: u8) -> char {
|
||||
}
|
||||
|
||||
/// Byte `b` of Mac Roman.
|
||||
pub(super) fn mac_roman(b: u8) -> char {
|
||||
pub(in crate::cmd) fn mac_roman(b: u8) -> char {
|
||||
const HIGH: [char; 128] = [
|
||||
'Ä', 'Å', 'Ç', 'É', 'Ñ', 'Ö', 'Ü', 'á', 'à', 'â', 'ä', 'ã', 'å', 'ç', 'é', 'è', //
|
||||
'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ñ', 'ó', 'ò', 'ô', 'ö', 'õ', 'ú', 'ù', 'û', 'ü', //
|
||||
|
||||
Reference in New Issue
Block a user