Preserve transparency in single-layer Photoshop TIFFs

This commit is contained in:
yoriswind committed 2026-12-01 03:01:38 -08:00
1 parent dd1f4d2936
commit d337a29e00
6 files changed
+190 -3

No files matched your search

Generated
+1
View File
@@ -8714,6 +8714,7 @@ dependencies = [
"craft-image-codecs",
"craft-jxl",
"craft-proof",
"craft-psd",
"craft-stream-codecs",
"craft-xml",
"crc32fast",
+31 -1
View File
@@ -10,11 +10,41 @@ pub type DecodedImage = (image::DynamicImage, Option<Vec<u8>>);
/// The renderer, File › Open and Place, SVG import, and embedded and linked images read images
/// with it.
pub fn decode_image(format: craft_image_codecs::Format, bytes: &[u8], allowance: u64) -> Result<DecodedImage, craft_image_codecs::CodecError> {
decoded_image(decode_source(format, bytes, allowance)?)
}
/// The two Photoshop tags associated with a selected TIFF image containing layers.
pub struct TiffPhotoshopLayers {
/// Tag 37724, carrying the Photoshop layers.
pub layers: Vec<u8>,
/// Tag 34377, carrying the Photoshop image resources.
pub image_resources: Option<Vec<u8>>,
}
/// The TIFF pixels and optional Photoshop layer data from the same selected directory.
pub fn decode_tiff_with_photoshop_layers(
bytes: &[u8],
allowance: u64,
) -> Result<(DecodedImage, Option<TiffPhotoshopLayers>), craft_image_codecs::CodecError> {
let mut image = decode_source(craft_image_codecs::Format::Tiff, bytes, allowance)?;
let photoshop =
image.meta.photoshop_layers.take().map(|layers| TiffPhotoshopLayers { layers, image_resources: image.meta.photoshop_resources.take() });
Ok((decoded_image(image)?, photoshop))
}
fn decode_source(
format: craft_image_codecs::Format,
bytes: &[u8],
allowance: u64,
) -> Result<craft_image_codecs::Image, craft_image_codecs::CodecError> {
let opts = craft_image_codecs::DecodeOptions {
limits: craft_image_codecs::Limits { max_width: u32::MAX, max_height: u32::MAX, max_pixels: u64::MAX, max_alloc: allowance },
keep_orientation: true,
};
let mut img = craft_image_codecs::decode_as_with(format, bytes, &opts)?;
craft_image_codecs::decode_as_with(format, bytes, &opts)
}
fn decoded_image(mut img: craft_image_codecs::Image) -> Result<DecodedImage, craft_image_codecs::CodecError> {
let icc = img.icc.take();
let img = dynamic(img).ok_or_else(|| craft_image_codecs::CodecError::InvalidImage("the decoded samples don't fit the image".into()))?;
Ok((img, icc))
+1
View File
@@ -51,6 +51,7 @@ vectorcraft-js = { workspace = true }
vectorcraft-apischema = { workspace = true }
image = { workspace = true }
craft-image-codecs = { workspace = true }
craft-psd = { workspace = true }
tiff = { workspace = true }
jxl-oxide = { workspace = true }
jxl-color = { workspace = true }
+16 -2
View File
@@ -1191,7 +1191,9 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
/// PNG keeps its gray or RGB samples at 8 or 16 bits, and the gray or RGB ICC profile they are in;
/// other samples become 8-bit RGBA. A PSD/PSB composite's stored image keeps its imported
/// clipping path ([`image_clip`]), and a PNG or TIFF that keeps such a path (as Unembed writes
/// it) is read with that path. A `.pcraft` document is read by [`super::pcraftread::image`].
/// it) is read with that path. An opaque RGB TIFF can recover transparency from a single
/// Photoshop layer when that layer reproduces its stored composite over white.
/// A `.pcraft` document is read by [`super::pcraftread::image`].
pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
if super::pcraftread::is_pcraft(bytes) {
return super::pcraftread::image(bytes);
@@ -1284,7 +1286,19 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
if pixels.saturating_mul(per_pixel) > MAX_RASTER_ALLOC || pixels * 4 > MAX_RASTER_ALLOC {
return Err(err(format!("an image of {w} × {h} pixels is too large to draw")));
}
let (img, profile) = vectorcraft_doc::decode::decode_image(kind, bytes, MAX_RASTER_ALLOC).map_err(err)?;
let (img, profile) = if f.id == "tiff" {
let ((img, profile), photoshop) =
vectorcraft_doc::decode::decode_tiff_with_photoshop_layers(bytes, MAX_RASTER_ALLOC).map_err(err)?;
let restored = match (&img, photoshop.as_ref()) {
(image::DynamicImage::ImageRgb8(flat), Some(photoshop)) => {
psdread::tiff_layer_transparency(flat, &photoshop.layers, photoshop.image_resources.as_deref(), MAX_RASTER_ALLOC)
}
_ => None,
};
(restored.map_or(img, image::DynamicImage::ImageRgba8), profile)
} else {
vectorcraft_doc::decode::decode_image(kind, bytes, MAX_RASTER_ALLOC).map_err(err)?
};
// A profile the decoder can't read leaves the image without one. A TIFF's profile is
// read by the TIFF reader, as before.
icc = match f.id {
+70
View File
@@ -224,6 +224,76 @@ const CLIPPING_PATH_NAME: u16 = 2999;
/// The saved paths' resource ids.
const SAVED_PATHS: std::ops::RangeInclusive<u16> = 2000..=2997;
/// Recovers the straight alpha of a plain Photoshop raster layer. Use it only if the stored
/// RGB composite exactly describes the same layer over white.
pub(super) fn tiff_layer_transparency(
flat: &image::RgbImage,
layers: &[u8],
image_resources: Option<&[u8]>,
allowance: u64,
) -> Option<image::RgbaImage> {
use craft_psd::{BlendMode, ColorMode, Compression, Header, ImageData, MaskData, tiff::ImageSourceData};
// Named clips have their own meaning. Limit the optional tag parse before allocation,
// including copies, parsed block records and byte-order conversion.
let (width, height) = flat.dimensions();
let canvas_bytes = (u64::from(width) * u64::from(height)).saturating_mul(7);
let resources_bytes = image_resources.map_or(0, |blocks| blocks.len() as u64);
let used = canvas_bytes.saturating_add(resources_bytes).saturating_add((layers.len() as u64).saturating_mul(32));
if layers.len() > 16 << 20
|| used > allowance
|| image_resources.is_some_and(|blocks| resources(blocks, true).any(|(id, _, _)| id == CLIPPING_PATH_NAME))
{
return None;
}
let (source, _) = ImageSourceData::from_bytes(layers).ok()?;
let [record] = source.layer_info.as_ref()?.layers.as_slice() else { return None };
let (layer_width, layer_height) = record.rect.size().ok()?;
// Layer::rgba8 keeps decoded color and alpha planes alongside its RGBA output.
let layer_bytes = layer_width.checked_mul(layer_height)?.checked_mul(9)? as u64;
let blend = &record.blending_ranges.data;
if used.saturating_add(layer_bytes) > allowance
|| !record.is_visible()
|| record.blend_mode != BlendMode::Normal
|| record.opacity != 255
|| record.clipping != 0
|| record.flags.pixel_data_irrelevant()
|| !matches!(&record.mask, MaskData::None)
|| !blend.len().is_multiple_of(8)
|| blend.chunks_exact(8).any(|range| range != [0, 0, 255, 255, 0, 0, 255, 255])
|| record.channels.len() != 4
|| [-1, 0, 1, 2].iter().any(|&id| record.channel(id).is_none())
|| record.extra_trailing.iter().any(|&byte| byte != 0)
|| record
.blocks
.iter()
.any(|block| !matches!(&block.key, b"luni" | b"lnsr" | b"lyid" | b"clbl" | b"infx" | b"knko" | b"lspf" | b"lclr" | b"shmd" | b"fxrp"))
|| source.layer_info_key != *b"Layr"
|| source.global_blocks.iter().any(|block| matches!(&block.key, b"Layr" | b"Lr16" | b"Lr32"))
{
return None;
}
let header = Header { version: source.version, reserved: [0; 6], channels: 3, height, width, depth: 8, color_mode: ColorMode::Rgb };
let file = source.into_psd(header, Vec::new(), ImageData::new(Compression::Raw, Vec::new()));
let layer = file.layer(0)?.rgba8().ok()?;
let pixels = image::RgbaImage::from_raw(layer.width, layer.height, layer.data)?;
let mut rgba = image::RgbaImage::new(width, height);
image::imageops::replace(&mut rgba, &pixels, i64::from(layer.left), i64::from(layer.top));
let mut transparent = false;
for (layer_pixel, flat_pixel) in rgba.pixels().zip(flat.pixels()) {
let alpha = u16::from(layer_pixel[3]);
transparent |= alpha < 255;
for channel in 0..3 {
let on_white = (u16::from(layer_pixel[channel]) * alpha + 255 * (255 - alpha) + 127) / 255;
if on_white != u16::from(flat_pixel[channel]) {
return None;
}
}
}
transparent.then_some(rgba)
}
/// The clipping path a PSD or PSB file names, in its pixel space (x across its width, y down
/// its height): the saved path (resources 2000 to 2997) whose name the clipping path resource
/// (2999) gives, both `8BIM` resources. `None` when the document names none, names a path it doesn't have, or that path
@@ -68,6 +68,77 @@ fn pixels(f: &[u8]) -> Vec<[u8; 4]> {
decode(f, 1 << 30, naive).unwrap().pixels().map(|p| p.0).collect()
}
/// A synthetic layered TIFF whose merged RGB image is the supplied composite and whose
/// Photoshop layer data is built independently from the layer pixels.
fn layered_tiff(layer: &[u8], composite: &[u8]) -> Vec<u8> {
use craft_psd::{LayerSpec, PixelData, PsdBuilder};
assert_eq!(layer.len() % 4, 0);
let layer_width = (layer.len() / 4) as u32;
let width = layer_width + 1;
assert_eq!(composite.len(), width as usize * 4);
let mut psd = PsdBuilder::new(width, 1);
psd.push_layer(LayerSpec::new("Synthetic layer", 1, 0, layer_width, 1, PixelData::Rgba8(layer.to_vec())));
psd.composite(PixelData::Rgba8(composite.to_vec()));
let mut psd = psd.build().unwrap();
let source = craft_psd::tiff::ImageSourceData::take_from_psd(&mut psd);
let (source, warnings) = source.into_bytes(craft_psd::tiff::ByteOrder::Little).unwrap();
assert!(warnings.is_empty());
let mut cursor = std::io::Cursor::new(Vec::new());
{
let mut encoder = tiff::encoder::TiffEncoder::new(&mut cursor).unwrap();
let mut image = encoder.new_image::<tiff::encoder::colortype::RGB8>(width, 1).unwrap();
image.encoder().write_tag(tiff::tags::Tag::Unknown(37724), source.as_slice()).unwrap();
image.write_data(&composite.chunks_exact(4).flat_map(|pixel| pixel[..3].iter().copied()).collect::<Vec<_>>()).unwrap();
}
cursor.into_inner()
}
/// Reads one image through the real file-open or linked-place command and checks the decoded alpha.
fn assert_tiff_layer_alpha(bytes: &[u8], linked_path: Option<&str>, expected: &[u8]) {
let mut session = Session::new();
let id = if let Some(path) = linked_path {
session.execute("file.new", &json!({"width": 20, "height": 20})).unwrap();
let result = session.execute("file.place", &json!({"path": path, "link": true})).unwrap();
let id = NodeId(result["ids"][0].as_u64().unwrap());
let NodeKind::Image(image) = &session.doc().unwrap().doc.node(id).unwrap().kind else { panic!("a linked image") };
assert!(image.link.is_some());
id
} else {
session.execute("document.open", &json!({"name": "layered.tif", "dataBase64": vectorcraft_format::base64_encode(bytes)})).unwrap();
session.doc().unwrap().doc.layers[0].children().unwrap()[0].id
};
let doc = &session.doc().unwrap().doc;
let NodeKind::Image(image) = &doc.node(id).unwrap().kind else { panic!("an image") };
let blob = doc.images.get(&image.key).unwrap();
let decoded = craft_image_codecs::decode(&blob.bytes).unwrap().to_rgba8();
assert_eq!(decoded.chunks_exact(4).map(|pixel| pixel[3]).collect::<Vec<_>>(), expected);
}
#[test]
fn layered_tiff_layer_alpha_is_restored_only_for_matching_white_composite() {
let layer = [
17, 29, 41, 0, // fully transparent
240, 32, 16, 128, // partially transparent
12, 200, 70, 255, // opaque
];
let composite = [255, 255, 255, 255, 255, 255, 255, 255, 247, 143, 135, 255, 12, 200, 70, 255];
let matching = layered_tiff(&layer, &composite);
assert_tiff_layer_alpha(&matching, None, &[0, 0, 128, 255]);
let dir = vectorcraft_testkit::TempDir::new("layered-tiff-alpha");
let path = write_file(&dir, "matching.tif", &matching);
assert_tiff_layer_alpha(&matching, Some(&path), &[0, 0, 128, 255]);
let mut different_composite = composite;
different_composite[4] ^= 1;
let mismatch = layered_tiff(&layer, &different_composite);
assert_tiff_layer_alpha(&mismatch, None, &[255, 255, 255, 255]);
let path = write_file(&dir, "mismatch.tif", &mismatch);
assert_tiff_layer_alpha(&mismatch, Some(&path), &[255, 255, 255, 255]);
}
#[test]
fn every_colour_mode_and_depth_reads() {
// Grayscale, 16 bits.