Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

TIFF: write and read EXIF as the file's own Exif and GPS directories (#4876)

Gert Pellin - GPE5064d80b1e2d
diff --git a/crates/codecs/src/codecs/mod.rs b/crates/codecs/src/codecs/mod.rs
index b0b3ca46e..afb7f9679 100644
--- a/crates/codecs/src/codecs/mod.rs
+++ b/crates/codecs/src/codecs/mod.rs
@@ -11,6 +11,7 @@ pub(crate) mod pcx;
pub(crate) mod png;
pub(crate) mod pnm;
pub(crate) mod tiff;
+pub(crate) mod tiff_exif;
pub(crate) mod tiff_ifd;
pub(crate) mod via_image;
pub(crate) mod vp8;
diff --git a/crates/codecs/src/codecs/tiff.rs b/crates/codecs/src/codecs/tiff.rs
index b2b315e26..5e09a68ec 100644
--- a/crates/codecs/src/codecs/tiff.rs
+++ b/crates/codecs/src/codecs/tiff.rs
@@ -35,6 +35,7 @@ use tiff::encoder::colortype::{self, ColorType as TiffColorType};
use tiff::encoder::{Rational, TiffEncoder, TiffKind, TiffKindBig, TiffKindStandard, TiffValue};
use tiff::tags::{PhotometricInterpretation, ResolutionUnit, SampleFormat, Tag, Type};
+use super::tiff_exif::{self, ExifDirs};
use super::tiff_ifd::{self as ifd, File, Ifd};
use crate::Format;
use crate::error::CodecError;
@@ -297,6 +298,13 @@ fn metadata(f: &File<'_>, dir: &Ifd, icc: &mut Option<Vec<u8>>) -> Metadata {
if dir.at == f.first_ifd { photoshop_tags(f.b) } else { (f.tag_bytes(dir, TAG_PHOTOSHOP), f.tag_bytes(dir, TAG_IMAGE_SOURCE_DATA)) };
meta.photoshop_resources = resources.map(<[u8]>::to_vec);
meta.photoshop_layers = layers.map(<[u8]>::to_vec);
+ // EXIF: the Exif and GPS directories IFD0 points to, with IFD0's descriptive tags, as an
+ // EXIF block (the other pages are reduced copies or layers of the same image).
+ if dir.at == f.first_ifd
+ && let Some(e) = tiff_exif::read(f.b).filter(ExifDirs::has_directories)
+ {
+ meta.exif = Some(tiff_exif::block(&e));
+ }
meta
}
@@ -1016,6 +1024,8 @@ custom_colortype!(CmykA32F, f32, PI::CMYK, &[32; 5], &[SampleFormat::IEEEFP; 5],
struct TagSet<'a> {
icc: Option<&'a [u8]>,
+ /// The EXIF block's directories and IFD0 tags, written as the TIFF's own.
+ exif: Option<ExifDirs>,
xmp: Option<&'a [u8]>,
dpi: Option<(f32, f32)>,
text: Vec<(Tag, &'a str)>,
@@ -1032,6 +1042,16 @@ where
[C::Inner]: TiffValue,
K: TiffKind,
{
+ // The Exif and GPS directories go before the image, outside its chain; IFD0 points to them.
+ let mut sub = |e: &ExifDirs, fields: &[tiff_exif::Field]| (!fields.is_empty()).then(|| tiff_exif::write_directory(enc, fields, e.le)).transpose();
+ let exif_at = match &tags.exif {
+ Some(e) => sub(e, &e.exif)?,
+ None => None,
+ };
+ let gps_at = match &tags.exif {
+ Some(e) => sub(e, &e.gps)?,
+ None => None,
+ };
let mut im = enc.new_image::<C>(w, h)?;
if let Some((x, y)) = tags.dpi {
im.resolution_unit(ResolutionUnit::Inch);
@@ -1052,6 +1072,17 @@ where
for (tag, s) in &tags.text {
d.write_tag(*tag, *s)?;
}
+ if let Some(e) = &tags.exif {
+ // The EXIF block's descriptive IFD0 tags, unless the text metadata already wrote them.
+ let ifd0: Vec<tiff_exif::Field> = e.ifd0.iter().filter(|f| !tags.text.iter().any(|(t, _)| t.to_u16() == f.tag)).cloned().collect();
+ tiff_exif::write_fields(d, &ifd0, e.le)?;
+ }
+ if let Some(at) = exif_at {
+ d.write_tag(Tag::Unknown(tiff_exif::TAG_EXIF_IFD), at)?;
+ }
+ if let Some(at) = gps_at {
+ d.write_tag(Tag::Unknown(tiff_exif::TAG_GPS_IFD), at)?;
+ }
if let Some(r) = tags.photoshop_resources {
d.write_tag(Tag::Unknown(TAG_PHOTOSHOP), r)?;
}
@@ -1099,7 +1130,8 @@ const CLASSIC_LIMIT: u64 = u32::MAX as u64;
/// room for the directory and strip tables.
fn estimated_size(img: &Image, tags: &TagSet<'_>) -> u64 {
let payloads = [tags.icc, tags.xmp, tags.photoshop_resources, tags.photoshop_layers].iter().flatten().map(|p| p.len() as u64).sum::<u64>();
- let text = tags.text.iter().map(|(_, s)| s.len() as u64).sum::<u64>();
+ let text = tags.text.iter().map(|(_, s)| s.len() as u64).sum::<u64>()
+ + tags.exif.iter().flat_map(|e| e.ifd0.iter().chain(&e.exif).chain(&e.gps)).map(|f| f.value.len() as u64 + 12).sum::<u64>();
// Strip tables: one offset and one count per strip of about 1 MB.
let tables = (img.data().len() as u64 / (1 << 20) + 1) * 16;
(img.data().len() as u64).saturating_add(payloads).saturating_add(text).saturating_add(tables).saturating_add(1 << 20)
@@ -1132,6 +1164,7 @@ pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result<Ve
let xmp = if opts.embed_metadata { img.meta.xmp.as_deref().map(|x| crate::resolution::export_xmp(x, img.meta.dpi)) } else { None };
let tags = TagSet {
icc: if opts.embed_icc { img.icc.as_deref() } else { None },
+ exif: if opts.embed_metadata { img.meta.exif.as_deref().and_then(|e| tiff_exif::read(crate::orientation::tiff_body(e))) } else { None },
xmp: xmp.as_deref().map(str::as_bytes),
dpi: if opts.embed_metadata { img.meta.dpi.filter(|d| d.0 > 0.0 && d.1 > 0.0) } else { None },
text,
diff --git a/crates/codecs/src/codecs/tiff_exif.rs b/crates/codecs/src/codecs/tiff_exif.rs
new file mode 100644
index 000000000..d07f555f3
--- /dev/null
+++ b/crates/codecs/src/codecs/tiff_exif.rs
@@ -0,0 +1,195 @@
+//! EXIF in a TIFF file: the Exif (34665) and GPS (34853) directories that IFD0 points to, plus
+//! IFD0's descriptive tags (make, model, software, artist, …), the way cameras and Photoshop
+//! write them.
+//!
+//! An EXIF block (`Metadata::exif`) is itself a small TIFF stream, so both directions go through
+//! the same reader ([`super::tiff_ifd::File`]): reading a TIFF builds a block from the file's own
+//! directories, writing one copies the block's directories into the file. Values are copied as
+//! bytes (re-ordered when the byte orders differ), so tags PhotoCraft doesn't know survive.
+//! Classic TIFF only on the reading side: an EXIF block has 4-byte offsets.
+
+use tiff::encoder::{DirectoryEncoder, TiffEncoder, TiffKind};
+use tiff::tags::{Tag, Type};
+use tiff::{Directory, TiffResult};
+
+use super::tiff_ifd::{File, Ifd};
+
+/// IFD0's pointer to the Exif directory.
+pub(crate) const TAG_EXIF_IFD: u16 = 34665;
+/// IFD0's pointer to the GPS directory.
+pub(crate) const TAG_GPS_IFD: u16 = 34853;
+/// The Exif directory's pointer to the Interoperability directory (not carried: it holds only
+/// the interoperability index, and a copied pointer would point nowhere).
+const TAG_INTEROP_IFD: u16 = 40965;
+/// IFD0 tags an EXIF block carries next to its directories: ImageDescription, Make, Model,
+/// Software, DateTime, Artist, Copyright. Structure, resolution and orientation belong to the
+/// image and are written from it.
+const IFD0_TAGS: [u16; 7] = [270, 271, 272, 305, 306, 315, 33432];
+/// At most this many entries are copied from one directory.
+const MAX_FIELDS: usize = 1024;
+
+/// One entry with its value bytes in the byte order of the stream it came from.
+#[derive(Clone, Debug, PartialEq)]
+pub(crate) struct Field {
+ pub tag: u16,
+ pub ty: u16,
+ pub count: u32,
+ pub value: Vec<u8>,
+}
+
+/// The EXIF parts of a TIFF stream, in its byte order (`le`).
+#[derive(Clone, Debug, Default, PartialEq)]
+pub(crate) struct ExifDirs {
+ pub le: bool,
+ pub ifd0: Vec<Field>,
+ pub exif: Vec<Field>,
+ pub gps: Vec<Field>,
+}
+
+impl ExifDirs {
+ /// Whether there is an Exif or GPS directory (IFD0's descriptive tags alone are not EXIF).
+ pub fn has_directories(&self) -> bool {
+ !self.exif.is_empty() || !self.gps.is_empty()
+ }
+}
+
+fn fields(f: &File<'_>, ifd: &Ifd, keep: impl Fn(u16) -> bool) -> Vec<Field> {
+ ifd.entries
+ .iter()
+ .filter(|e| keep(e.tag) && !matches!(e.tag, TAG_EXIF_IFD | TAG_GPS_IFD | TAG_INTEROP_IFD))
+ .filter_map(|e| Some(Field { tag: e.tag, ty: e.ty, count: u32::try_from(e.count).ok()?, value: f.data(e)?.to_vec() }))
+ .take(MAX_FIELDS)
+ .collect()
+}
+
+fn sub(f: &File<'_>, ifd: &Ifd, tag: u16) -> Option<Ifd> {
+ let at = f.tag_uint(ifd, tag)?;
+ (at != ifd.at).then(|| f.ifd(at)).flatten()
+}
+
+/// The EXIF parts of the classic TIFF stream `b` (a TIFF file, or an EXIF block without its
+/// `Exif\0\0` prefix): IFD0's descriptive tags and the Exif and GPS directories.
+pub(crate) fn read(b: &[u8]) -> Option<ExifDirs> {
+ let f = File::parse(b)?;
+ if f.big {
+ return None;
+ }
+ let ifd0 = f.ifd(f.first_ifd)?;
+ let dir = |tag: u16| sub(&f, &ifd0, tag).map(|d| fields(&f, &d, |_| true)).unwrap_or_default();
+ Some(ExifDirs { le: f.le, ifd0: fields(&f, &ifd0, |t| IFD0_TAGS.contains(&t)), exif: dir(TAG_EXIF_IFD), gps: dir(TAG_GPS_IFD) })
+}
+
+/// Bytes per element whose order a byte-order change reverses: a RATIONAL is two LONGs.
+fn element(ty: u16) -> usize {
+ match ty {
+ 3 | 8 => 2,
+ 4 | 5 | 9 | 10 | 11 | 13 => 4,
+ 12 | 16 | 17 | 18 => 8,
+ _ => 1,
+ }
+}
+
+/// `value` of type `ty` in byte order `to_le`, from `from_le`.
+pub(crate) fn reorder(ty: u16, value: &[u8], from_le: bool, to_le: bool) -> Vec<u8> {
+ let n = element(ty);
+ if from_le == to_le || n == 1 {
+ return value.to_vec();
+ }
+ value.chunks(n).flat_map(|c| c.iter().rev().copied()).collect()
+}
+
+/// An EXIF block: a classic TIFF stream in `dirs.le` order whose IFD0 holds `dirs.ifd0` and
+/// points to the Exif and GPS directories.
+pub(crate) fn block(dirs: &ExifDirs) -> Vec<u8> {
+ let le = dirs.le;
+ let u16b = |v: u16| if le { v.to_le_bytes() } else { v.to_be_bytes() };
+ let u32b = |v: u32| if le { v.to_le_bytes() } else { v.to_be_bytes() };
+ let mut ifd0: Vec<Field> = dirs.ifd0.clone();
+ // Placeholders for the pointers; their offsets are known once the layout is.
+ let pointer = |tag: u16| Field { tag, ty: 4, count: 1, value: vec![0; 4] };
+ if !dirs.exif.is_empty() {
+ ifd0.push(pointer(TAG_EXIF_IFD));
+ }
+ if !dirs.gps.is_empty() {
+ ifd0.push(pointer(TAG_GPS_IFD));
+ }
+ // Layout: header, then each directory followed by its out-of-line values.
+ let size = |fs: &[Field]| 2 + 12 * fs.len() + 4 + fs.iter().filter(|f| f.value.len() > 4).map(|f| f.value.len().next_multiple_of(2)).sum::<usize>();
+ let at0 = 8;
+ let at_exif = at0 + size(&ifd0);
+ let at_gps = at_exif + if dirs.exif.is_empty() { 0 } else { size(&dirs.exif) };
+ for f in &mut ifd0 {
+ match f.tag {
+ TAG_EXIF_IFD => f.value = u32b(at_exif as u32).to_vec(),
+ TAG_GPS_IFD => f.value = u32b(at_gps as u32).to_vec(),
+ _ => {}
+ }
+ }
+ let mut out = Vec::new();
+ out.extend_from_slice(if le { b"II" } else { b"MM" });
+ out.extend_from_slice(&u16b(42));
+ out.extend_from_slice(&u32b(at0 as u32));
+ let write_dir = |out: &mut Vec<u8>, fs: &[Field]| {
+ let mut fs = fs.to_vec();
+ fs.sort_by_key(|f| f.tag);
+ let start = out.len();
+ let mut extra = start + 2 + 12 * fs.len() + 4;
+ let mut values = Vec::new();
+ out.extend_from_slice(&u16b(fs.len() as u16));
+ for f in &fs {
+ out.extend_from_slice(&u16b(f.tag));
+ out.extend_from_slice(&u16b(f.ty));
+ out.extend_from_slice(&u32b(f.count));
+ if f.value.len() <= 4 {
+ let mut inline = f.value.clone();
+ inline.resize(4, 0);
+ out.extend_from_slice(&inline);
+ } else {
+ out.extend_from_slice(&u32b(extra as u32));
+ values.extend_from_slice(&f.value);
+ if f.value.len() % 2 == 1 {
+ values.push(0);
+ }
+ extra += f.value.len().next_multiple_of(2);
+ }
+ }
+ out.extend_from_slice(&u32b(0));
+ out.extend_from_slice(&values);
+ };
+ write_dir(&mut out, &ifd0);
+ if !dirs.exif.is_empty() {
+ write_dir(&mut out, &dirs.exif);
+ }
+ if !dirs.gps.is_empty() {
+ write_dir(&mut out, &dirs.gps);
+ }
+ out
+}
+
+/// Writes `fields` (in byte order `from_le`) into a directory of `enc` that is not part of the
+/// page chain, and returns its offset for the pointer tag.
+pub(crate) fn write_directory<W: std::io::Write + std::io::Seek, K: TiffKind>(
+ enc: &mut TiffEncoder<W, K>,
+ fields: &[Field],
+ from_le: bool,
+) -> TiffResult<K::OffsetType> {
+ let mut sub = enc.extra_directory()?;
+ write_fields(&mut sub, fields, from_le)?;
+ Ok(sub.finish_with_offsets()?.offset)
+}
+
+/// Adds `fields` (in byte order `from_le`) to directory `d`, in the file's (native) byte order.
+pub(crate) fn write_fields<W: std::io::Write + std::io::Seek, K: TiffKind>(
+ d: &mut DirectoryEncoder<'_, W, K>,
+ fields: &[Field],
+ from_le: bool,
+) -> TiffResult<()> {
+ let mut dir = Directory::empty();
+ for f in fields {
+ let Some(ty) = Type::from_u16(f.ty) else { continue };
+ let entry = d.write_entry_bytes(ty, &reorder(f.ty, &f.value, from_le, cfg!(target_endian = "little")))?;
+ dir.extend([(Tag::from_u16_exhaustive(f.tag), entry)]);
+ }
+ d.extend_from(&dir);
+ Ok(())
+}
diff --git a/crates/codecs/src/format.rs b/crates/codecs/src/format.rs
index dca235f80..d3730c08f 100644
--- a/crates/codecs/src/format.rs
+++ b/crates/codecs/src/format.rs
@@ -233,7 +233,7 @@ pub fn caps(format: Format) -> FormatCaps {
FormatCaps { depths: &[S::U8, S::U16], layouts: RGB_GRAY, icc: true, exif: true, xmp: true, dpi: true, text: true, animation: true, ..base }
}
Format::Jpeg => FormatCaps { layouts: &[L::Gray, L::Rgb, L::Cmyk], alpha: false, icc: true, exif: true, xmp: true, dpi: true, lossy: true, ..base },
- Format::Tiff => FormatCaps { depths: &[S::U8, S::U16, S::F32], layouts: ALL_LAYOUTS, icc: true, xmp: true, dpi: true, text: true, ..base },
+ Format::Tiff => FormatCaps { depths: &[S::U8, S::U16, S::F32], layouts: ALL_LAYOUTS, icc: true, exif: true, xmp: true, dpi: true, text: true, ..base },
Format::WebP => FormatCaps { icc: true, exif: true, xmp: true, animation: true, ..base },
Format::Gif => FormatCaps { layouts: &[L::Rgba], animation: true, lossy: true, ..base },
Format::Bmp => base,
diff --git a/crates/codecs/tests/metadata.rs b/crates/codecs/tests/metadata.rs
index 76ff9c938..d8f4d80a9 100644
--- a/crates/codecs/tests/metadata.rs
+++ b/crates/codecs/tests/metadata.rs
@@ -34,7 +34,11 @@ fn check_format(format: Format) {
} else {
assert!(warnings.contains(&FidelityWarning::IccDropped), "{format:?}");
}
- if c.exif {
+ if c.exif && format == Format::Tiff {
+ // TIFF writes the block's directories as its own and rebuilds a block from them on
+ // reading (tests/tiff_exif.rs); IFD0's orientation here is the image's.
+ assert!(!warnings.contains(&FidelityWarning::ExifDropped), "{format:?}");
+ } else if c.exif {
assert_eq!(back.meta.exif, img.meta.exif, "{format:?} exif");
} else {
assert!(warnings.contains(&FidelityWarning::ExifDropped), "{format:?}");
diff --git a/crates/codecs/tests/tiff_exif.rs b/crates/codecs/tests/tiff_exif.rs
new file mode 100644
index 000000000..92e8c91df
--- /dev/null
+++ b/crates/codecs/tests/tiff_exif.rs
@@ -0,0 +1,168 @@
+//! EXIF in TIFF: an EXIF block's Exif and GPS directories and IFD0's descriptive tags are
+//! written as the TIFF's own directories (IFD0 pointing to them, as cameras and Photoshop write
+//! them) and read back into a block.
+
+use photocraft_codecs::*;
+
+/// A classic TIFF stream builder for EXIF blocks: directories of (tag, type, count, value bytes).
+struct Block {
+ le: bool,
+}
+
+type Entry = (u16, u16, u32, Vec<u8>);
+
+impl Block {
+ fn u16(&self, v: u16) -> [u8; 2] {
+ if self.le { v.to_le_bytes() } else { v.to_be_bytes() }
+ }
+ fn u32(&self, v: u32) -> [u8; 4] {
+ if self.le { v.to_le_bytes() } else { v.to_be_bytes() }
+ }
+ fn rational(&self, n: u32, d: u32) -> Vec<u8> {
+ [self.u32(n), self.u32(d)].concat()
+ }
+ /// IFD0 (with pointers to `exif` and `gps` appended) followed by the two directories.
+ fn build(&self, mut ifd0: Vec<Entry>, exif: Vec<Entry>, gps: Vec<Entry>) -> Vec<u8> {
+ let size = |d: &[Entry]| 2 + 12 * d.len() + 4 + d.iter().filter(|e| e.3.len() > 4).map(|e| e.3.len().next_multiple_of(2)).sum::<usize>();
+ ifd0.push((34665, 4, 1, vec![0; 4]));
+ ifd0.push((34853, 4, 1, vec![0; 4]));
+ let at_exif = 8 + size(&ifd0);
+ let at_gps = at_exif + size(&exif);
+ let n = ifd0.len();
+ ifd0[n - 2].3 = self.u32(at_exif as u32).to_vec();
+ ifd0[n - 1].3 = self.u32(at_gps as u32).to_vec();
+ let mut out = if self.le { b"II".to_vec() } else { b"MM".to_vec() };
+ out.extend(self.u16(42));
+ out.extend(self.u32(8));
+ for d in [ifd0, exif, gps] {
+ let start = out.len();
+ let mut extra = start + 2 + 12 * d.len() + 4;
+ let mut values = Vec::new();
+ out.extend(self.u16(d.len() as u16));
+ for (tag, ty, count, v) in &d {
+ out.extend(self.u16(*tag));
+ out.extend(self.u16(*ty));
+ out.extend(self.u32(*count));
+ if v.len() <= 4 {
+ let mut inline = v.clone();
+ inline.resize(4, 0);
+ out.extend(inline);
+ } else {
+ out.extend(self.u32(extra as u32));
+ values.extend(v);
+ if v.len() % 2 == 1 {
+ values.push(0);
+ }
+ extra += v.len().next_multiple_of(2);
+ }
+ }
+ out.extend(self.u32(0));
+ out.extend(values);
+ }
+ out
+ }
+}
+
+/// The entries (tag, type, count, value bytes in the block's order) of IFD0 and of the
+/// directories its tags `34665` and `34853` point to.
+fn dirs(b: &[u8]) -> (bool, Vec<Entry>, Vec<Entry>, Vec<Entry>) {
+ let le = &b[..2] == b"II";
+ let u16 = |at: usize| if le { u16::from_le_bytes([b[at], b[at + 1]]) } else { u16::from_be_bytes([b[at], b[at + 1]]) };
+ let u32 = |at: usize| {
+ let s = [b[at], b[at + 1], b[at + 2], b[at + 3]];
+ if le { u32::from_le_bytes(s) } else { u32::from_be_bytes(s) }
+ };
+ let size = |ty: u16| match ty {
+ 3 | 8 => 2,
+ 4 | 9 | 11 | 13 => 4,
+ 5 | 10 | 12 => 8,
+ _ => 1,
+ };
+ let read = |at: usize| -> Vec<Entry> {
+ (0..usize::from(u16(at)))
+ .map(|i| {
+ let e = at + 2 + 12 * i;
+ let (tag, ty, count) = (u16(e), u16(e + 2), u32(e + 4));
+ let len = count as usize * size(ty);
+ let at = if len <= 4 { e + 8 } else { u32(e + 8) as usize };
+ (tag, ty, count, b[at..at + len].to_vec())
+ })
+ .collect()
+ };
+ let ifd0 = read(u32(4) as usize);
+ let sub = |tag: u16| ifd0.iter().find(|e| e.0 == tag).map(|e| read(u32_of(&e.3, le) as usize)).unwrap_or_default();
+ let (exif, gps) = (sub(34665), sub(34853));
+ (le, ifd0.into_iter().filter(|e| !matches!(e.0, 34665 | 34853)).collect(), exif, gps)
+}
+
+fn u32_of(v: &[u8], le: bool) -> u32 {
+ let s = [v[0], v[1], v[2], v[3]];
+ if le { u32::from_le_bytes(s) } else { u32::from_be_bytes(s) }
+}
+
+/// The entries of `d` with their values in little-endian order, sorted by tag.
+fn normalized(d: &[Entry], le: bool) -> Vec<(u16, u16, u32, Vec<u8>)> {
+ let swap = |ty: u16, v: &[u8]| -> Vec<u8> {
+ let n = match ty {
+ 3 | 8 => 2,
+ 4 | 5 | 9 | 10 | 11 | 13 => 4,
+ 12 => 8,
+ _ => 1,
+ };
+ if le || n == 1 { v.to_vec() } else { v.chunks(n).flat_map(|c| c.iter().rev().copied()).collect() }
+ };
+ let mut v: Vec<_> = d.iter().map(|e| (e.0, e.1, e.2, swap(e.1, &e.3))).collect();
+ v.sort_by_key(|e| e.0);
+ v
+}
+
+fn camera_block(le: bool) -> Vec<u8> {
+ let b = Block { le };
+ let ascii = |s: &str| [s.as_bytes(), b"\0"].concat();
+ b.build(
+ vec![(271, 2, 4, ascii("Cam")), (272, 2, 9, ascii("Model X1")), (315, 2, 16, ascii("A. Photographer")), (274, 3, 1, b.u16(1).to_vec())],
+ vec![
+ (33434, 5, 1, b.rational(1, 125)),
+ (34855, 3, 1, b.u16(200).to_vec()),
+ (36867, 2, 20, ascii("2026:10:13 09:30:00")),
+ (37386, 5, 1, b.rational(50, 1)),
+ (37500, 7, 6, b"maker!".to_vec()),
+ ],
+ vec![(1, 2, 2, ascii("N")), (2, 5, 3, [b.rational(51, 1), b.rational(30, 1), b.rational(0, 1)].concat())],
+ )
+}
+
+#[test]
+fn exif_round_trips_through_a_tiff_in_either_byte_order() {
+ for le in [true, false] {
+ let block = camera_block(le);
+ let mut img = Image::from_raw(4, 3, ChannelLayout::Rgb, SampleType::U8, vec![90; 36]).unwrap();
+ img.meta.exif = Some(block.clone());
+ let tiff = encode(&img, Format::Tiff, &EncodeOptions::default()).unwrap();
+ assert!(fidelity_warnings(&img, Format::Tiff).iter().all(|w| *w != FidelityWarning::ExifDropped));
+ let back = decode(&tiff).unwrap().meta.exif.expect("EXIF read back");
+ let (ble, b0, bexif, bgps) = dirs(&back);
+ let (ole, o0, oexif, ogps) = dirs(&block);
+ assert_eq!(normalized(&bexif, ble), normalized(&oexif, ole), "Exif directory (le {le})");
+ assert_eq!(normalized(&bgps, ble), normalized(&ogps, ole), "GPS directory (le {le})");
+ // IFD0's descriptive tags come along; its orientation is the image's own.
+ let descriptive: Vec<_> = o0.into_iter().filter(|e| e.0 != 274).collect();
+ assert_eq!(normalized(&b0, ble), normalized(&descriptive, ole), "IFD0 (le {le})");
+ }
+}
+
+#[test]
+fn a_tiff_without_exif_directories_reads_no_exif() {
+ let mut img = Image::from_raw(2, 2, ChannelLayout::Gray, SampleType::U8, vec![0; 4]).unwrap();
+ img.meta.text = vec![("Artist".into(), "A. Photographer".into())];
+ let tiff = encode(&img, Format::Tiff, &EncodeOptions::default()).unwrap();
+ assert_eq!(decode(&tiff).unwrap().meta.exif, None);
+}
+
+#[test]
+fn no_exif_is_written_without_embed_metadata() {
+ let mut img = Image::from_raw(2, 2, ChannelLayout::Gray, SampleType::U8, vec![0; 4]).unwrap();
+ img.meta.exif = Some(camera_block(true));
+ let tiff = encode(&img, Format::Tiff, &EncodeOptions { embed_metadata: false, ..Default::default() }).unwrap();
+ assert_eq!(decode(&tiff).unwrap().meta.exif, None);
+}
diff --git a/crates/io/src/tiff_layers.rs b/crates/io/src/tiff_layers.rs
index 0aca0fe88..8a5810e92 100644
--- a/crates/io/src/tiff_layers.rs
+++ b/crates/io/src/tiff_layers.rs
@@ -213,7 +213,8 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions, ctl: &photocr
ctl.progress(TIFF_LAYERS_DONE);
warnings.extend(w.into_iter().map(|w| format!("layer data: {w}")));
// The profile and XMP are written as TIFF tags, not as resources. EXIF stays a resource
- // (1058): the TIFF codec has no EXIF directory, and the PSD importer reads it back from there.
+ // (1058), which the PSD importer reads back unchanged; a block rebuilt from the TIFF's own
+ // Exif directory keeps only the Exif, GPS and descriptive tags.
let resources: Vec<ImageResource> = file.resources.iter().filter(|r| !matches!(r.id, ids::ICC_PROFILE | ids::XMP)).cloned().collect();
let resources = resources_to_bytes(&resources)?;
@@ -235,10 +236,10 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions, ctl: &photocr
let mut img = Image::from_raw(w, h, layout, sample, data)?;
img.icc = doc.icc_profile.as_ref().map(|i| i.to_vec());
img.meta = codecs::Metadata {
- // EXIF is deliberately not set here: the TIFF codec has no EXIF directory, so the tags
- // above carry it as resource 1058 and the importer reads them back from there. Handing the
- // codec a second copy in `meta.exif` bought nothing and made the export claim it would
- // drop metadata it had in fact kept (#1545).
+ // EXIF is deliberately not set here: the tags above carry it as resource 1058 and the
+ // importer reads it back from there unchanged. A second copy in `meta.exif` (the codec's
+ // Exif directory) would be read back in its place, rebuilt without the thumbnail and IFD0
+ // orientation (#1545).
xmp: doc.metadata.xmp.clone().filter(|_| opts.xmp == crate::XmpEmbed::All),
text: if opts.xmp == crate::XmpEmbed::All { doc.metadata.text.clone() } else { Vec::new() },
dpi: Some((doc.resolution_dpi, doc.resolution_dpi)),
diff --git a/crates/io/tests/tiff_layers.rs b/crates/io/tests/tiff_layers.rs
index 913ab2f39..56e51bf9f 100644
--- a/crates/io/tests/tiff_layers.rs
+++ b/crates/io/tests/tiff_layers.rs
@@ -127,7 +127,7 @@ fn exif() -> Vec<u8> {
}
/// #1545: a layered TIFF carries EXIF as Photoshop resource 1058 and reads it back, so it must
-/// not report a loss it never makes. A flat TIFF really does lose the tags and still says so.
+/// not report a loss it never makes. A flat TIFF writes it as its own tags and keeps it too.
#[test]
fn layered_tiff_keeps_exif_without_claiming_a_loss() {
let mut d = gen_doc(ColorMode::Rgb, SampleType::U8, Features::PIXELS);
@@ -140,9 +140,13 @@ fn layered_tiff_keeps_exif_without_claiming_a_loss() {
let kept = back.metadata.exif.as_deref().expect("EXIF survives the layered export");
assert!(kept.windows(ARTIST.len()).any(|w| w == ARTIST), "the Artist tag did not survive: {kept:?}");
- // The control from the issue: the flat path drops it for real, and keeps reporting that.
+ // The flat path writes the EXIF block's tags as the TIFF's own (here IFD0's Artist, which
+ // reads back as the document's Artist text), so it reports no loss either.
let flat = tiff(&d, false);
- assert!(flat.warnings.iter().any(|w| w.contains("EXIF")), "a flat TIFF really does lose EXIF: {:?}", flat.warnings);
+ assert!(!flat.warnings.iter().any(|w| w.contains("EXIF")), "a flat TIFF keeps EXIF: {:?}", flat.warnings);
+ let back = import("x.tif", &flat.bytes).unwrap().document;
+ let artist = std::str::from_utf8(ARTIST).unwrap().trim_end_matches('\0');
+ assert!(back.metadata.text.iter().any(|(k, v)| k == "Artist" && v == artist), "{:?}", back.metadata.text);
}
#[test]