PhotoCraft: An open-source, photo editor written by scratch in pure Rust
TGA: a 32-bit Targa opens with its alpha as "Alpha 1", as in Photoshop (#2225) (#2482)
MrCloudy276e3cbd0102c
diff --git a/crates/engine/src/video_cmds.rs b/crates/engine/src/video_cmds.rsindex 250ab8616..242a3bea1 100644--- a/crates/engine/src/video_cmds.rs+++ b/crates/engine/src/video_cmds.rs@@ -207,7 +207,11 @@ fn load_frames(path: &str, fmt: photocraft_color::PixelFormat) -> Result<Vec<Surfor f in &files {let bytes = std::fs::read(f).map_err(|e| EngineError::Other(format!("read `{}`: {e}", f.display())))?;let name = f.to_string_lossy();- let doc = crate::file_cmds::import(&name, &bytes)?;+ let mut doc = crate::file_cmds::import(&name, &bytes)?;+ // A Targa's alpha opens as a channel (as in Photoshop); a frame's alpha is transparency.+ if f.extension().is_some_and(|e| e.eq_ignore_ascii_case("tga")) {+ photocraft_io::tga_alpha_channel_to_transparency(&mut doc);+ }frames.push(crate::file_cmds::flattened(&doc, fmt));}Ok(frames)diff --git a/crates/engine/src/video_cmds/tests.rs b/crates/engine/src/video_cmds/tests.rsindex 190aa306e..097adb7c4 100644--- a/crates/engine/src/video_cmds/tests.rs+++ b/crates/engine/src/video_cmds/tests.rs@@ -203,3 +203,31 @@ fn render_writer_progress_and_cancellation_leave_session_unchanged() {assert_eq!(s.active().unwrap().doc.timeline, before.timeline);}}++/// A 16×12 32-bit Targa: red, alpha 255 on the left half and 0 on the right.+fn write_tga(path: &str) {+ let mut b = vec![0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 12, 0, 32, 8];+ for _y in 0..12 {+ for x in 0..16 {+ b.extend_from_slice(&[0, 0, 255, if x < 8 { 255 } else { 0 }]);+ }+ }+ std::fs::write(path, b).unwrap();+}++/// #2225: a Targa opens with its alpha as an "Alpha 1" channel (as in Photoshop), but an image+/// sequence treats a frame's alpha as transparency, as video footage does, so TGA sequences+/// keep their transparent areas.+#[test]+fn tga_sequence_frames_keep_their_transparency() {+ let dir = tmpdir("tga");+ write_tga(&format!("{dir}/f01.tga"));+ write_tga(&format!("{dir}/f02.tga"));+ let frames = load_frames(&dir, photocraft_color::PixelFormat::new(photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8, true)).unwrap();+ assert_eq!(frames.len(), 2);+ for f in &frames {+ assert_eq!(f.pixel(2, 6), vec![1.0, 0.0, 0.0, 1.0]);+ assert_eq!(f.pixel(12, 6)[3], 0.0, "the right half stays transparent");+ }+ let _ = std::fs::remove_dir_all(&dir);+}diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rsindex 7c328288f..cbd4c44c9 100644--- a/crates/io/src/flat.rs+++ b/crates/io/src/flat.rs@@ -21,6 +21,9 @@ pub fn import_flat(name: &str, bytes: &[u8]) -> Result<ImportResult, IoError> {}let img = codecs::decode(bytes)?;let mut r = image_to_document(name, &img)?;+ if codecs::detect(bytes) == Some(Format::Tga) && img.layout() == ChannelLayout::Rgba {+ tga_alpha_to_channel(&mut r.document)?;+ }// OpenEXR and Radiance HDR hold linear, scene-referred values (Rec. 709 primaries unless// stated otherwise, and an OpenEXR `Y` is linear luminance): tag them linear sRGB or linear// gray so they display and convert correctly.@@ -35,6 +38,72 @@ pub fn import_flat(name: &str, bytes: &[u8]) -> Result<ImportResult, IoError> {Ok(r)}+/// Photoshop opens a 32-bit Targa as an opaque Background plus an "Alpha 1" channel holding the+/// fourth byte, even when the header declares no alpha bits, and keeps the stored colours (#2225;+/// measured on Photoshop 27.11). Layer transparency would hide those colours and lose the channel+/// on the next save, where only an alpha channel becomes the Targa's alpha.+fn tga_alpha_to_channel(doc: &mut Document) -> Result<(), IoError> {+ let canvas = doc.bounds();+ let depth = doc.depth;+ let Some(layer) = doc.layers.first_mut() else { return Ok(()) };+ let LayerContent::Raster(s) = &mut layer.content else { return Ok(()) };+ let ch = s.format().channels();+ if !s.format().alpha || ch < 2 {+ return Ok(());+ }+ let mut alpha = Surface::new(PixelFormat::new(ColorMode::Grayscale, depth, false));+ // A band of rows at a time: no full-size float copy of the image.+ let rows = (BAND_BYTES / (canvas.width().max(1) as usize * ch * 4)).max(1) as i32;+ let mut y = canvas.y0;+ while y < canvas.y1 {+ let r = Rect::new(canvas.x0, y, canvas.x1, y.saturating_add(rows).min(canvas.y1));+ let mut px = s.read_region(r);+ let a: Vec<f32> = px.chunks_exact_mut(ch).map(|p| p.last_mut().map_or(1.0, |a| std::mem::replace(a, 1.0))).collect();+ s.write_region(r, &px);+ alpha.write_region(r, &a);+ y = r.y1;+ }+ s.prune();+ alpha.prune();+ layer.name = "Background".into();+ layer.locks.transparency = true;+ layer.locks.position = true;+ doc.channels.push(photocraft_doc::AlphaChannel::new("Alpha 1", alpha));+ Ok(())+}++/// Undoes [`tga_alpha_to_channel`] for a document a Targa just opened as: the "Alpha 1" channel+/// becomes the layer's transparency again. For image sequences, which treat a frame's alpha as+/// transparency, as video footage does (Photoshop's Interpret Footage). Anything else is left+/// alone.+pub fn tga_alpha_channel_to_transparency(doc: &mut Document) {+ let canvas = doc.bounds();+ let ([layer], [channel]) = (&mut doc.layers[..], &doc.channels[..]) else { return };+ let LayerContent::Raster(s) = &mut layer.content else { return };+ let ch = s.format().channels();+ if !s.format().alpha || ch < 2 || channel.spot.is_some() {+ return;+ }+ let rows = (BAND_BYTES / (canvas.width().max(1) as usize * ch * 4)).max(1) as i32;+ let mut y = canvas.y0;+ while y < canvas.y1 {+ let r = Rect::new(canvas.x0, y, canvas.x1, y.saturating_add(rows).min(canvas.y1));+ let mut px = s.read_region(r);+ for (p, a) in px.chunks_exact_mut(ch).zip(channel.surface.read_region(r)) {+ if let Some(last) = p.last_mut() {+ *last = a;+ }+ }+ s.write_region(r, &px);+ y = r.y1;+ }+ s.prune();+ layer.name = "Layer 0".into();+ layer.locks.transparency = false;+ layer.locks.position = false;+ doc.channels.clear();+}+/// Opens one page of a TIFF or BigTIFF file: `None` is the page Photoshop opens (the first/// full-resolution one), `Some(i)` an index into [`codecs::tiff_info`]'s pages (every IFD and/// SubIFD). A page with Photoshop layer data opens layered.diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rsindex c9971c7e3..3d6b766af 100644--- a/crates/io/src/lib.rs+++ b/crates/io/src/lib.rs@@ -62,7 +62,7 @@ use photocraft_doc::Document;use photocraft_psd::{PsdError, PsdFile};pub use adjust_map::ADJUSTMENT_KEYS;-pub use flat::{document_to_image, import_tiff_page};+pub use flat::{document_to_image, import_tiff_page, tga_alpha_channel_to_transparency};pub use psd_export::{PsdExportOptions, document_to_psd, document_to_psd_with};pub use psd_import::{psd_to_document, psd_to_document_with};diff --git a/crates/io/tests/flat.rs b/crates/io/tests/flat.rsindex 78ff91ca2..6fb4dd958 100644--- a/crates/io/tests/flat.rs+++ b/crates/io/tests/flat.rs@@ -43,7 +43,6 @@ codec_rt!(png_rgb8_opaque, "png", ColorMode::Rgb, SampleType::U8, false, 0.0);codec_rt!(png_rgba16, "png", ColorMode::Rgb, SampleType::U16, true, 0.0);codec_rt!(png_gray8, "png", ColorMode::Grayscale, SampleType::U8, false, 0.0);codec_rt!(png_graya16, "png", ColorMode::Grayscale, SampleType::U16, true, 0.0);-codec_rt!(tga_rgba8, "tga", ColorMode::Rgb, SampleType::U8, true, 0.0);codec_rt!(tga_rgb8_opaque, "tga", ColorMode::Rgb, SampleType::U8, false, 0.0);codec_rt!(tga_gray8, "tga", ColorMode::Grayscale, SampleType::U8, false, 0.0);codec_rt!(tiff_rgba8, "tiff", ColorMode::Rgb, SampleType::U8, true, 0.0);@@ -525,9 +524,71 @@ fn tga_writes_the_alpha_channel_as_32_bit_alpha() {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]);+ assert_eq!(b[3], 1.0, "{depth:?} the Background stays opaque");}+ // Round trip, as in Photoshop: the alpha opens back as the "Alpha 1" channel (#2225).+ let [ch] = &back.channels[..] else { panic!("{depth:?}: one alpha channel, got {}", back.channels.len()) };+ assert_eq!(ch.name, "Alpha 1");+ for (i, a) in ch.surface.read_region(back.bounds()).iter().enumerate() {+ assert!((a - alpha_value(i as u32 % 9)).abs() <= 0.5 / 255.0, "{depth:?} alpha {i}: {a}");+ }+ }+}++/// A 64×64 uncompressed Targa (bottom-left origin), byte for byte like the files the Photoshop+/// measurements in #2225 opened: red everywhere, alpha (when `bpp` is 32) 255 on the left half and+/// 0 on the right, with `alpha_bits` in the descriptor.+fn tga_file(bpp: u8, alpha_bits: u8) -> Vec<u8> {+ let mut b = vec![0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 0, 64, 0, bpp, alpha_bits];+ for _y in 0..64 {+ for x in 0..64 {+ b.extend_from_slice(&[0, 0, 255]);+ if bpp == 32 {+ b.push(if x < 32 { 255 } else { 0 });+ }+ }+ }+ b+}++/// #2225, measured on Photoshop 27.11: a 32-bit Targa opens as an opaque, locked Background plus+/// an "Alpha 1" channel holding the fourth byte (also when the descriptor declares 0 alpha bits),+/// and the stored colours stay visible where the alpha is 0. A 24-bit Targa has no channel.+#[test]+fn tga_32_bit_opens_its_alpha_as_a_channel_like_photoshop() {+ for alpha_bits in [8, 0] {+ let d = import("a.tga", &tga_file(32, alpha_bits)).unwrap().document;+ let [bg] = &d.layers[..] else { panic!("one layer") };+ assert_eq!(bg.name, "Background", "alpha bits {alpha_bits}");+ assert!(bg.locks.transparency && bg.locks.position);+ let px = bg.surface().unwrap().read_region(d.bounds());+ for (i, p) in px.as_chunks::<4>().0.iter().enumerate() {+ assert_eq!(*p, [1.0, 0.0, 0.0, 1.0], "alpha bits {alpha_bits}: pixel {i} keeps its red, opaque");+ }+ let [ch] = &d.channels[..] else { panic!("alpha bits {alpha_bits}: one channel, got {}", d.channels.len()) };+ assert_eq!((ch.name.as_str(), ch.spot), ("Alpha 1", None));+ let a = ch.surface.read_region(d.bounds());+ assert_eq!((a[64 * 32 + 10], a[64 * 32 + 54]), (1.0, 0.0), "alpha bits {alpha_bits}");+ }+ let d = import("a.tga", &tga_file(24, 0)).unwrap().document;+ assert!(d.channels.is_empty());+ assert_eq!(d.layers[0].name, "Background");+}++/// Layer transparency is still written as the Targa's alpha when there is no alpha channel (a+/// choice left to the maintainers in #2225); the file opens back as Photoshop opens it, with the+/// alpha as "Alpha 1" and the colours of transparent pixels kept.+#[test]+fn tga_transparency_reopens_as_alpha_1() {+ let d = single(ColorMode::Rgb, SampleType::U8, true);+ let r = export(&d, "a.tga", &ExportOptions::default()).unwrap();+ let back = import("a.tga", &r.bytes).unwrap().document;+ let src = d.layers[0].surface().unwrap().read_region(d.bounds());+ let got = back.layers[0].surface().unwrap().read_region(back.bounds());+ let alpha = back.channels.first().expect("Alpha 1").surface.read_region(back.bounds());+ for (i, ((s, g), a)) in src.as_chunks::<4>().0.iter().zip(got.as_chunks::<4>().0.iter()).zip(&alpha).enumerate() {+ assert_eq!(&g[..3], &s[..3], "colour {i}");+ assert_eq!((g[3], *a), (1.0, s[3]), "alpha {i}");}}