mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
This commit is contained in:
commit
c247a34bb6
6 files changed
+205
-7
No files matched your search
@@ -163,19 +163,29 @@ fn info_and_convert_report_decode_warnings() {
|
||||
gif.extend_from_slice(b"\x2C\0\0\0\0\x01\0\x01\0\0\x02\x02\x44\x01\0");
|
||||
}
|
||||
gif.push(0x3B);
|
||||
// A GIF opens in Indexed Color (#7886), so `convert` to PNG also notes the palette PNG it
|
||||
// writes, after the decode warning.
|
||||
let cases = [
|
||||
("whole.jpg", &jpeg[..], None),
|
||||
("half.jpg", &jpeg[..jpeg.len() / 2], Some("JPEG data ends early (the file is truncated or damaged); part of the image is missing")),
|
||||
("anim.gif", &gif[..], Some("only the first of 3 frames was imported")),
|
||||
("whole.jpg", &jpeg[..], None, None),
|
||||
("half.jpg", &jpeg[..jpeg.len() / 2], Some("JPEG data ends early (the file is truncated or damaged); part of the image is missing"), None),
|
||||
("anim.gif", &gif[..], Some("only the first of 3 frames was imported"), Some("written as an 8-bit palette PNG (2 colours)")),
|
||||
];
|
||||
for (name, bytes, warning) in cases {
|
||||
for (name, bytes, warning, export) in cases {
|
||||
let file = d.join(name);
|
||||
std::fs::write(&file, bytes).unwrap();
|
||||
let (out, _) = ok(bin().arg("info").arg(&file).arg("--compact"));
|
||||
let v: Value = serde_json::from_str(&out).unwrap();
|
||||
assert_eq!(v["warnings"], json!(warning.into_iter().collect::<Vec<_>>()), "{name}");
|
||||
let (_, err) = ok(bin().arg("convert").arg(&file).arg(d.join(format!("{name}.png"))));
|
||||
assert_eq!(err.trim(), warning.map(|w| format!("warning: {w}")).unwrap_or_default(), "{name}");
|
||||
let expected: Vec<String> = warning.into_iter().chain(export).map(|w| format!("warning: {w}")).collect();
|
||||
assert_eq!(
|
||||
err.trim(),
|
||||
expected.join(
|
||||
"
|
||||
"
|
||||
),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
std::fs::remove_dir_all(d).unwrap();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
//! The colour table of a GIF, read from its blocks without decoding pixels (GIF89a
|
||||
//! specification: Logical Screen Descriptor, Global and Local Color Tables, Graphic Control
|
||||
//! Extension).
|
||||
//!
|
||||
//! A GIF is always palette-based, so it opens in Indexed Color with the table of the frame that
|
||||
//! [`crate::decode`] keeps, the first: its Local Color Table when it has one, else the Global
|
||||
//! one, and the transparent entry that frame's Graphic Control Extension names.
|
||||
|
||||
/// Colours of the table the first frame uses, and its transparent entry. `None` for anything
|
||||
/// that isn't a well-formed GIF up to its first image, or a first frame without a table.
|
||||
pub(crate) fn palette(b: &[u8]) -> Option<(Vec<[u8; 3]>, Option<u8>)> {
|
||||
if !(b.starts_with(b"GIF87a") || b.starts_with(b"GIF89a")) {
|
||||
return None;
|
||||
}
|
||||
// Logical Screen Descriptor: width, height, packed fields, background, aspect.
|
||||
let packed = *b.get(10)?;
|
||||
let mut at = 13;
|
||||
let table = |at: usize, packed: u8| -> Option<Vec<[u8; 3]>> {
|
||||
let n = 2usize << (packed & 0x07);
|
||||
let bytes = b.get(at..at.checked_add(n.checked_mul(3)?)?)?;
|
||||
Some(bytes.as_chunks::<3>().0.to_vec())
|
||||
};
|
||||
let global = if packed & 0x80 != 0 {
|
||||
let t = table(at, packed)?;
|
||||
at += t.len() * 3;
|
||||
Some(t)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut transparent = None;
|
||||
loop {
|
||||
match *b.get(at)? {
|
||||
// Extension: label, then data sub-blocks up to a zero-length one.
|
||||
0x21 => {
|
||||
let label = *b.get(at + 1)?;
|
||||
at += 2;
|
||||
// Graphic Control Extension: block size 4, packed (bit 0: transparent colour
|
||||
// given), delay (2 bytes), transparent colour index.
|
||||
if label == 0xF9 && *b.get(at)? == 4 {
|
||||
let flags = *b.get(at + 1)?;
|
||||
transparent = (flags & 0x01 != 0).then_some(*b.get(at + 4)?);
|
||||
}
|
||||
loop {
|
||||
let size = usize::from(*b.get(at)?);
|
||||
at = at.checked_add(1 + size)?;
|
||||
if size == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Image Descriptor: position and size (8 bytes), packed fields, then the Local Color
|
||||
// Table if bit 7 is set. This is the first frame: its table is the one used.
|
||||
0x2C => {
|
||||
let packed = *b.get(at + 9)?;
|
||||
let colors = if packed & 0x80 != 0 { table(at + 10, packed)? } else { global? };
|
||||
let transparent = transparent.filter(|i| usize::from(*i) < colors.len());
|
||||
return Some((colors, transparent));
|
||||
}
|
||||
// Trailer, or anything else: no image.
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::palette;
|
||||
|
||||
/// A GIF up to its first image: `global` table entries, optional GCE transparency, optional
|
||||
/// local table.
|
||||
fn gif(global: &[[u8; 3]], transparent: Option<u8>, local: Option<&[[u8; 3]]>) -> Vec<u8> {
|
||||
let size_bits = |n: usize| (n.max(2).next_power_of_two().trailing_zeros() - 1) as u8;
|
||||
let mut b = b"GIF89a".to_vec();
|
||||
b.extend([4, 0, 4, 0]);
|
||||
b.push(if global.is_empty() { 0 } else { 0x80 | size_bits(global.len()) });
|
||||
b.extend([0, 0]);
|
||||
let pad = |b: &mut Vec<u8>, t: &[[u8; 3]]| {
|
||||
let n = 2usize << size_bits(t.len());
|
||||
for k in 0..n {
|
||||
b.extend(t.get(k).copied().unwrap_or([0, 0, 0]));
|
||||
}
|
||||
};
|
||||
if !global.is_empty() {
|
||||
pad(&mut b, global);
|
||||
}
|
||||
// A comment extension first, to skip.
|
||||
b.extend([0x21, 0xFE, 3, b'h', b'i', b'!', 0]);
|
||||
if let Some(i) = transparent {
|
||||
b.extend([0x21, 0xF9, 4, 0x01, 0, 0, i, 0]);
|
||||
}
|
||||
b.extend([0x2C, 0, 0, 0, 0, 4, 0, 4, 0]);
|
||||
match local {
|
||||
Some(t) => {
|
||||
b.push(0x80 | size_bits(t.len()));
|
||||
pad(&mut b, t);
|
||||
}
|
||||
None => b.push(0),
|
||||
}
|
||||
b.extend([2, 2, 0x4C, 0x01, 0, 0x3B]);
|
||||
b
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_frames_table_and_transparent_entry() {
|
||||
let g = [[255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 255]];
|
||||
assert_eq!(palette(&gif(&g, None, None)), Some((g.to_vec(), None)));
|
||||
assert_eq!(palette(&gif(&g, Some(2), None)), Some((g.to_vec(), Some(2))));
|
||||
// A local table wins over the global one.
|
||||
let l = [[1, 2, 3], [4, 5, 6]];
|
||||
assert_eq!(palette(&gif(&g, Some(1), Some(&l))), Some((l.to_vec(), Some(1))));
|
||||
// A transparent index past the table is no transparent entry.
|
||||
assert_eq!(palette(&gif(&l, Some(9), None)), Some((l.to_vec(), None)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_table_or_not_a_gif_is_none() {
|
||||
assert_eq!(palette(&gif(&[], None, None)), None, "no table at all");
|
||||
assert_eq!(palette(b"\x89PNG\r\n\x1a\n"), None);
|
||||
assert_eq!(palette(b""), None);
|
||||
let whole = gif(&[[9, 9, 9], [8, 8, 8]], Some(0), None);
|
||||
for cut in 0..whole.len() - 6 {
|
||||
// Cut short anywhere before the image descriptor's fields: never a panic.
|
||||
let _ = palette(&whole[..cut]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ pub(crate) mod exr;
|
||||
pub(crate) mod exr_cryptomatte;
|
||||
pub(crate) mod fits;
|
||||
pub(crate) mod gif_frames;
|
||||
pub(crate) mod gif_palette;
|
||||
pub(crate) mod heif;
|
||||
pub(crate) mod jpeg;
|
||||
pub(crate) mod pcx;
|
||||
|
||||
@@ -128,6 +128,12 @@ pub fn probe_size(bytes: &[u8]) -> Result<(u32, u32), CodecError> {
|
||||
Ok(if (5..=8).contains(&o) { (h, w) } else { (w, h) })
|
||||
}
|
||||
|
||||
/// The colour table of a GIF's first frame (its Local Color Table, else the Global one) and the
|
||||
/// entry its Graphic Control Extension makes transparent, read without decoding pixels.
|
||||
pub fn gif_palette(bytes: &[u8]) -> Option<(Vec<[u8; 3]>, Option<u8>)> {
|
||||
crate::codecs::gif_palette::palette(bytes)
|
||||
}
|
||||
|
||||
/// Returns the embedded colour table for an indexed BMP, if it has one.
|
||||
pub fn bmp_palette(bytes: &[u8]) -> Result<Option<Vec<[u8; 3]>>, CodecError> {
|
||||
via_image::bmp_palette(bytes)
|
||||
|
||||
@@ -22,11 +22,12 @@ pub fn import_flat(name: &str, bytes: &[u8]) -> Result<ImportResult, IoError> {
|
||||
return import_tiff_page(name, bytes, None);
|
||||
}
|
||||
let img = codecs::decode_as(format.ok_or(codecs::CodecError::UnknownFormat)?, bytes)?;
|
||||
// A palette BMP or PNG opens in Indexed Color mode with its colour table, as in Photoshop
|
||||
// (#3802, #4804).
|
||||
// A palette BMP, PNG or GIF opens in Indexed Color mode with its colour table, as in
|
||||
// Photoshop (#3802, #4804, #7886). A GIF is always palette-based: the first frame's table.
|
||||
let palette = match format {
|
||||
Some(Format::Bmp) => codecs::bmp_palette(bytes).ok().flatten().map(|c| (c, None)),
|
||||
Some(Format::Png) => codecs::png_palette(bytes).ok().flatten().map(|p| (p.colors, p.transparent)),
|
||||
Some(Format::Gif) => codecs::gif_palette(bytes),
|
||||
_ => None,
|
||||
};
|
||||
let mut r = image_to_document(name, &img)?;
|
||||
|
||||
@@ -118,6 +118,60 @@ fn indexed_png_opens_with_its_color_table() {
|
||||
assert_eq!(s.rgba(0, 1)[3], 0.0, "the tRNS entry is transparent");
|
||||
}
|
||||
|
||||
/// A 2 × 2 GIF89a of palette indices `idx` over `pal` (padded to 4 entries), with `transparent`
|
||||
/// set through a Graphic Control Extension. Its LZW stream clears before every pixel, so every
|
||||
/// code stays 3 bits: the simplest valid stream any decoder reads.
|
||||
fn indexed_gif(pal: &[[u8; 3]; 4], idx: [u8; 4], transparent: Option<u8>) -> Vec<u8> {
|
||||
let mut b = b"GIF89a".to_vec();
|
||||
b.extend([2, 0, 2, 0, 0x81, 0, 0]); // 2 × 2, global table of 4
|
||||
pal.iter().for_each(|c| b.extend(c));
|
||||
if let Some(t) = transparent {
|
||||
b.extend([0x21, 0xF9, 4, 0x01, 0, 0, t, 0]);
|
||||
}
|
||||
b.extend([0x2C, 0, 0, 0, 0, 2, 0, 2, 0, 0]);
|
||||
let (clear, end) = (4u32, 5u32);
|
||||
let codes: Vec<u32> = idx.iter().flat_map(|&i| [clear, u32::from(i)]).chain([end]).collect();
|
||||
let (mut bits, mut n, mut data) = (0u32, 0u32, Vec::new());
|
||||
for c in codes {
|
||||
bits |= c << n;
|
||||
n += 3;
|
||||
while n >= 8 {
|
||||
data.push((bits & 0xFF) as u8);
|
||||
bits >>= 8;
|
||||
n -= 8;
|
||||
}
|
||||
}
|
||||
if n > 0 {
|
||||
data.push(bits as u8);
|
||||
}
|
||||
b.push(2); // LZW minimum code size
|
||||
b.push(data.len() as u8);
|
||||
b.extend(&data);
|
||||
b.extend([0, 0x3B]);
|
||||
b
|
||||
}
|
||||
|
||||
/// An indexed GIF opens in Indexed Color mode with its colour table and transparent entry, as a
|
||||
/// palette PNG does (#7886); it used to open as RGB.
|
||||
#[test]
|
||||
fn indexed_gif_opens_with_its_color_table() {
|
||||
let pal = [[10, 20, 30], [200, 100, 50], [7, 8, 9], [0, 255, 0]];
|
||||
let doc = import("indexed.gif", &indexed_gif(&pal, [1, 0, 2, 1], Some(2))).unwrap().document;
|
||||
assert_eq!(doc.mode, ColorMode::Indexed);
|
||||
assert_eq!(doc.depth, SampleType::U8);
|
||||
let table = doc.color_table.as_ref().unwrap();
|
||||
assert_eq!(table.colors, pal, "every entry, used or not");
|
||||
assert_eq!(table.transparent, Some(2));
|
||||
let s = doc.layers[0].surface().unwrap();
|
||||
let px = s.rgba(0, 0);
|
||||
assert!((px[0] - 200.0 / 255.0).abs() < 1e-6 && (px[3] - 1.0).abs() < 1e-6, "{px:?}");
|
||||
assert_eq!(s.rgba(0, 1)[3], 0.0, "the transparent entry is transparent");
|
||||
// Without a transparent entry, the table alone.
|
||||
let doc = import("opaque.gif", &indexed_gif(&pal, [3, 3, 0, 1], None)).unwrap().document;
|
||||
assert_eq!(doc.mode, ColorMode::Indexed);
|
||||
assert_eq!(doc.color_table.as_ref().unwrap().transparent, None);
|
||||
}
|
||||
|
||||
/// FITS header cards travel as the document's text metadata, so an astro frame keeps its
|
||||
/// OBJECT, EXPTIME and the rest through an edit.
|
||||
#[test]
|
||||
|
||||
Reference in new issue
Block a user