Merge pull request #10888 from dotCooCoo/fix/targa-color-model

Targa export: a Color Model option writes grayscale files
This commit is contained in:
.CooCoo authored and GitHub committed 2026-12-04 22:27:33 -08:00
commit 4a7fe04e81
11 files changed
+181 -41

No files matched your search

+30 -4
View File
@@ -1,4 +1,4 @@
//! Targa export: depths, alpha and the footer.
//! Targa export: depths, grayscale, alpha and the footer.
use super::on_white;
use super::tests_bmp::{art, decode, u16_at};
@@ -9,7 +9,7 @@ fn targa_depths_alpha_and_footer() {
let (w, h) = (7, 3);
let px = art(w, h);
for (depth, alpha_bits) in [(16, 1), (24, 0), (32, 8)] {
let file = tga::encode(&px, w, h, &TgaOptions { depth }).unwrap();
let file = tga::encode(&px, w, h, &TgaOptions { depth, gray: false }).unwrap();
assert_eq!((file[2], file[16], file[17]), (2, depth, alpha_bits), "true colour, the depth byte, alpha bits");
assert_eq!((u16_at(&file, 12), u16_at(&file, 14)), (7, 3));
assert_eq!(file.len(), 18 + (w * h) as usize * usize::from(depth / 8) + 26);
@@ -18,13 +18,39 @@ fn targa_depths_alpha_and_footer() {
assert_eq!(img.dimensions(), (w, h));
let want = on_white(px[(2 * w as usize + 3) * 4..][..4].try_into().unwrap());
let got = img.get_pixel(3, 2).0;
assert!(got[..3].iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 8), "depth {depth}: {got:?} vs {want:?}");
for c in 0..3 {
assert!(got[c].abs_diff(want[c]) <= 8, "depth {depth}, channel {c}: {got:?} vs {want:?}");
}
match depth {
32 => assert_eq!((img.get_pixel(0, 0).0[3], img.get_pixel(1, 0).0[3]), (0, 128), "8-bit alpha"),
24 => assert_eq!(img.get_pixel(0, 0).0, [255; 4], "flattened on white"),
_ => {}
}
}
assert!(tga::encode(&px, w, h, &TgaOptions { depth: 8 }).is_err());
assert!(tga::encode(&px, w, h, &TgaOptions { depth: 8, gray: false }).is_err());
assert!(tga::encode(&px, 70_000, 1, &TgaOptions::default()).is_err(), "too wide");
}
/// Grayscale Targa files are image type 3: 8 bits flattened on white, or 16 with an 8-bit alpha.
#[test]
fn targa_grayscale_writes_lightness() {
let (w, h) = (7, 3);
let px = art(w, h);
for (depth, alpha_bits) in [(8, 0), (16, 8)] {
let file = tga::encode(&px, w, h, &TgaOptions { depth, gray: true }).unwrap();
assert_eq!((file[2], file[16], file[17]), (3, depth, alpha_bits), "grayscale, the depth byte, alpha bits");
assert_eq!(file.len(), 18 + (w * h) as usize * usize::from(depth / 8) + 26);
let img = decode(&file, craft_image_codecs::Format::Tga);
assert_eq!(img.dimensions(), (w, h));
// (0, 2) is opaque red 230, 40, 30: Rec. 601 lightness 96, the same in every channel.
let [r, g, b, a] = img.get_pixel(0, 2).0;
assert!(r == g && g == b && r.abs_diff(96) <= 1 && a == 255, "depth {depth}: {:?}", [r, g, b, a]);
match depth {
8 => assert_eq!(img.get_pixel(0, 0).0, [255; 4], "flattened on white"),
_ => assert_eq!((img.get_pixel(0, 0).0[3], img.get_pixel(1, 0).0[3]), (0, 128), "8-bit alpha"),
}
}
for depth in [24, 32] {
assert!(tga::encode(&px, w, h, &TgaOptions { depth, gray: true }).is_err(), "{depth} bits gray");
}
}
+39 -15
View File
@@ -1,33 +1,55 @@
//! Targa export: uncompressed true colour at 16 bits per pixel (5-5-5 and a one-bit alpha), 24 or
//! 32 (8-bit alpha), rows bottom-up, with the version 2 footer.
//! 32 (8-bit alpha), or uncompressed grayscale at 8 bits or 16 (8-bit alpha), rows bottom-up, with
//! the version 2 footer.
use super::on_white;
use super::quantize::luma;
/// Bits per pixel a Targa export can have.
/// Bits per pixel a true-colour Targa export can have.
pub const DEPTHS: [u8; 3] = [16, 24, 32];
/// Bits per pixel a grayscale Targa export can have.
pub const GRAY_DEPTHS: [u8; 2] = [8, 16];
/// The Targa options of a raster export.
#[derive(Clone, Debug, PartialEq)]
pub struct TgaOptions {
/// Bits per pixel ([`DEPTHS`]).
/// Bits per pixel ([`DEPTHS`], or [`GRAY_DEPTHS`] when `gray`).
pub depth: u8,
/// Grayscale (image type 3) instead of true colour (image type 2).
pub gray: bool,
}
impl Default for TgaOptions {
fn default() -> Self {
Self { depth: 24 }
Self { depth: Self::default_depth(false), gray: false }
}
}
impl TgaOptions {
/// The depth a colour model starts with: 24 bits for true colour, 8 for grayscale.
pub fn default_depth(gray: bool) -> u8 {
if gray { 8 } else { 24 }
}
/// The depths the colour model can be written at.
pub fn depths(gray: bool) -> &'static [u8] {
if gray { &GRAY_DEPTHS } else { &DEPTHS }
}
/// Why these options can't be written, if they can't.
pub fn check(&self) -> Result<(), String> {
if DEPTHS.contains(&self.depth) { Ok(()) } else { Err(format!("Targa depth {}: 16, 24 or 32 bits per pixel", self.depth)) }
match (self.gray, Self::depths(self.gray).contains(&self.depth)) {
(_, true) => Ok(()),
(false, false) => Err(format!("Targa depth {}: 16, 24 or 32 bits per pixel", self.depth)),
(true, false) => Err(format!("grayscale Targa depth {}: 8 or 16 bits per pixel", self.depth)),
}
}
}
/// Straight-alpha RGBA pixels as a Targa file. 24 bits blend partly transparent pixels over white;
/// at 16 bits a pixel is opaque from half opacity up, else transparent.
/// Straight-alpha RGBA pixels as a Targa file. 24 bits and 8-bit grayscale blend partly
/// transparent pixels over white; at 16 bits true colour a pixel is opaque from half opacity up,
/// else transparent.
pub fn encode(rgba: &[u8], width: u32, height: u32, o: &TgaOptions) -> Result<Vec<u8>, String> {
o.check()?;
let (Ok(w16), Ok(h16)) = (u16::try_from(width), u16::try_from(height)) else {
@@ -40,21 +62,23 @@ pub fn encode(rgba: &[u8], width: u32, height: u32, o: &TgaOptions) -> Result<Ve
}
let px = rgba.as_chunks::<4>().0;
let mut out = Vec::with_capacity((w * h).saturating_mul(usize::from(o.depth / 8)).saturating_add(18 + 26));
// No image id or colour map, uncompressed true colour, origin (0, 0).
out.extend([0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
// No image id or colour map, uncompressed true colour (2) or grayscale (3), origin (0, 0).
out.extend([0, 0, if o.gray { 3 } else { 2 }, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
out.extend(w16.to_le_bytes());
out.extend(h16.to_le_bytes());
// Bits per pixel, then the alpha bits (rows bottom-up, left to right).
let alpha_bits = match o.depth {
16 => 1,
32 => 8,
let alpha_bits = match (o.gray, o.depth) {
(false, 16) => 1,
(true, 16) | (false, 32) => 8,
_ => 0,
};
out.extend([o.depth, alpha_bits]);
for row in px.chunks(w).rev() {
for p in row {
match o.depth {
16 => {
match (o.gray, o.depth) {
(true, 8) => out.push(luma(on_white(p))),
(true, _) => out.extend([luma([p[0], p[1], p[2]]), p[3]]),
(false, 16) => {
let v = if p[3] >= 128 {
let [r, g, b] = [p[0], p[1], p[2]].map(|c| u16::from(c >> 3));
0x8000 | r << 10 | g << 5 | b
@@ -63,7 +87,7 @@ pub fn encode(rgba: &[u8], width: u32, height: u32, o: &TgaOptions) -> Result<Ve
};
out.extend(v.to_le_bytes());
}
24 => {
(false, 24) => {
let [r, g, b] = on_white(p);
out.extend([b, g, r]);
}