diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs index 8d0921c8c0c..52f37fe7776 100644 --- a/crates/io/src/flat.rs +++ b/crates/io/src/flat.rs @@ -323,9 +323,63 @@ pub fn export_flat(doc: &Document, format: Format, opts: &ExportOptions) -> Resu warnings.push(format!("colours converted to sRGB; {format:?} can't embed the document's colour profile")); } } + if format == Format::Tga { + img = tga_alpha_channel(doc, img, &mut warnings)?; + } encode_image(&img, format, opts, warnings) } +/// Photoshop's 32-bit Targa takes its alpha from the document's alpha channel, not from layer +/// transparency: with exactly one alpha channel (spot channels don't count) an RGB file gets +/// that channel's values as its alpha, and its colours are the composite over white. With two or +/// more Photoshop writes no channel (an opaque alpha), so the image is left as it is. Grayscale +/// Targas have no alpha in Photoshop either. +fn tga_alpha_channel(doc: &Document, img: Image, warnings: &mut Vec) -> Result { + if !img.layout().is_rgb() { + return Ok(img); + } + let mut alphas = doc.channels.iter().filter(|c| c.spot.is_none()); + let channel = match (alphas.next(), alphas.next()) { + (Some(c), None) => c, + (Some(_), Some(_)) => { + warnings.push("Targa holds one alpha channel; with several, none was written (as in Photoshop)".into()); + return Ok(img); + } + _ => return Ok(img), + }; + let img = if img.layout().has_alpha() { + warnings.push("transparency composited over white; the alpha channel is the Targa's alpha".into()); + matte_over_white(&img)? + } else { + img + }; + let (w, h) = img.dimensions(); + let canvas = doc.bounds(); + if canvas.width() != w || canvas.height() != h { + return Err(IoError::Unsupported("the composite and the alpha channel differ in size".into())); + } + let sample = img.sample_type(); + let row = img.data().len() / (h.max(1) as usize); + let band = (BAND_BYTES / row.max(1)).max(1); + let stride = channel.surface.channels().max(1); + let mut data = try_buffer(img.pixel_count(), ChannelLayout::Rgba.channels() * sample.bytes())?; + let mut y0 = canvas.y0; + for rows in img.data().chunks(row.max(1) * band) { + let n = (rows.len() / row.max(1)) as u32; + let y1 = y0.saturating_add(i32::try_from(n).unwrap_or(i32::MAX)); + let alpha = channel.surface.read_region(Rect::new(canvas.x0, y0, canvas.x1, y1)); + let rgb = Image::from_raw(w, n, img.layout(), sample, rows.to_vec())?.to_normalized(); + let mut vals = Vec::with_capacity(rgb.len() / 3 * 4); + for (px, a) in rgb.as_chunks::<3>().0.iter().zip(alpha.chunks_exact(stride)) { + vals.extend_from_slice(px); + vals.push(a.first().copied().unwrap_or(1.0)); + } + data.extend_from_slice(Image::from_normalized(w, n, ChannelLayout::Rgba, sample, &vals)?.data()); + y0 = y1; + } + Ok(Image::from_raw(w, h, ChannelLayout::Rgba, sample, data)?.with_icc(img.icc.clone()).with_meta(img.meta.clone())) +} + /// Encodes a flat codec image as `format`: the fidelity warnings, then the codec. The end of /// every flat export, and of a layered TIFF (whose composite is a flat image to other readers), /// so export-wide policies on the image's metadata apply to both. diff --git a/crates/io/tests/flat.rs b/crates/io/tests/flat.rs index 7f1624c6250..28a2c04a1b3 100644 --- a/crates/io/tests/flat.rs +++ b/crates/io/tests/flat.rs @@ -429,3 +429,90 @@ fn animation_imports_the_first_frame_with_a_warning() { assert_eq!(three.warnings, ["only the first of 3 frames was imported"]); pixels_eq(&one.document, &three.document, 0.0); } + +/// Alpha channel values for the #2124 tests: white (selected) on the left, mid grey, black. +fn alpha_value(x: u32) -> f32 { + match x { + 0..=3 => 1.0, + 4 => g(128), + _ => 0.0, + } +} + +/// `d` with one alpha channel holding [`alpha_value`] (Photoshop's "Alpha 1"). +fn with_alpha_channel(mut d: photocraft_doc::Document, name: &str) -> photocraft_doc::Document { + let fmt = photocraft_color::PixelFormat::new(ColorMode::Grayscale, d.depth, false); + let mut s = photocraft_raster::Surface::new(fmt); + let r = d.bounds(); + let vals: Vec = (r.y0..r.y1).flat_map(|_| (r.x0..r.x1).map(|x| alpha_value(x as u32))).collect(); + s.write_region(r, &vals); + d.channels.push(photocraft_doc::AlphaChannel::new(name, s)); + d +} + +/// Header and decoded pixels of a TGA file. +fn tga(bytes: &[u8]) -> (u8, u8, photocraft_codecs::Image) { + (bytes[16], bytes[17] & 0x0f, photocraft_codecs::decode(bytes).expect("decode tga")) +} + +/// #2124: Photoshop writes the document's alpha channel as a 32-bit Targa's alpha (8 alpha bits +/// in the descriptor), and the file opens back with that alpha. 16-bit documents are written as +/// 8-bit Targa without panicking. +#[test] +fn tga_writes_the_alpha_channel_as_32_bit_alpha() { + for depth in [SampleType::U8, SampleType::U16] { + let d = with_alpha_channel(single(ColorMode::Rgb, depth, false), "Alpha 1"); + let r = export(&d, "a.tga", &ExportOptions::default()).unwrap(); + let (bpp, alpha_bits, img) = tga(&r.bytes); + assert_eq!((bpp, alpha_bits), (32, 8), "{depth:?}"); + assert_eq!(img.layout(), photocraft_codecs::ChannelLayout::Rgba, "{depth:?}"); + let (w, _) = img.dimensions(); + for (i, px) in img.data().as_chunks::<4>().0.iter().enumerate() { + let x = i as u32 % w; + assert_eq!(px[3], (alpha_value(x) * 255.0).round() as u8, "{depth:?} pixel {i}"); + } + // The colours are the document's (opaque Background, untouched by the alpha). + let want = single(ColorMode::Rgb, SampleType::U8, false); + let back = import("a.tga", &r.bytes).unwrap().document; + let (sa, sb) = (want.layers[0].surface().unwrap(), back.layers[0].surface().unwrap()); + let (va, vb) = (sa.read_region(want.bounds()), sb.read_region(back.bounds())); + for (i, (a, b)) in va.as_chunks::<4>().0.iter().zip(vb.as_chunks::<4>().0.iter()).enumerate() { + assert!(a[..3].iter().zip(&b[..3]).all(|(p, q)| (p - q).abs() <= 1.0 / 255.0), "{depth:?} colour {i}: {a:?} {b:?}"); + // Round trip: the alpha opens back as the layer's transparency. + assert!((b[3] - alpha_value(i as u32 % 9)).abs() <= 0.5 / 255.0, "{depth:?} alpha {i}: {}", b[3]); + } + } +} + +/// #2124: as in Photoshop, the alpha channel (not layer transparency) is the alpha; transparent +/// pixels are composited over white. Spot channels are not alpha channels. +#[test] +fn tga_alpha_channel_wins_over_transparency_and_skips_spot_channels() { + let mut d = with_alpha_channel(single(ColorMode::Rgb, SampleType::U8, true), "Alpha 2"); + let spot = photocraft_raster::Surface::new(photocraft_color::PixelFormat::new(ColorMode::Grayscale, SampleType::U8, false)); + let spot = + photocraft_doc::AlphaChannel { spot: Some((photocraft_color::Color::rgb(1.0, 0.0, 0.0), 1.0)), ..photocraft_doc::AlphaChannel::new("Spot", spot) }; + d.channels.insert(0, spot); + let r = export(&d, "a.tga", &ExportOptions::default()).unwrap(); + let (bpp, alpha_bits, img) = tga(&r.bytes); + assert_eq!((bpp, alpha_bits), (32, 8)); + let src = d.layers[0].surface().unwrap().read_region(d.bounds()); + for (i, (px, s)) in img.data().as_chunks::<4>().0.iter().zip(src.as_chunks::<4>().0.iter()).enumerate() { + assert_eq!(px[3], (alpha_value(i as u32 % 9) * 255.0).round() as u8, "alpha {i}"); + let over_white = s[0] * s[3] + 1.0 - s[3]; + assert!((f32::from(px[0]) / 255.0 - over_white).abs() <= 1.0 / 255.0, "red {i}: {} vs {over_white}", px[0]); + } +} + +/// #2124: Photoshop writes no channel as the alpha when there are several, and grayscale Targas +/// have no alpha at all. +#[test] +fn tga_ignores_several_alpha_channels_and_grayscale() { + let d = with_alpha_channel(with_alpha_channel(single(ColorMode::Rgb, SampleType::U8, false), "Alpha 1"), "Alpha 2"); + let r = export(&d, "a.tga", &ExportOptions::default()).unwrap(); + assert_eq!(tga(&r.bytes).0, 24); + assert!(r.warnings.iter().any(|w| w.contains("one alpha channel")), "{:?}", r.warnings); + let d = with_alpha_channel(single(ColorMode::Grayscale, SampleType::U8, false), "Alpha 1"); + let r = export(&d, "a.tga", &ExportOptions::default()).unwrap(); + assert_eq!(tga(&r.bytes).0, 8); +}