Skip to content

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

fix(codecs): WebP export keeps the resolution (#8775)

FinnNkdef4646c0e41
diff --git a/crates/codecs/src/codecs/webp.rs b/crates/codecs/src/codecs/webp.rs
index 42afce314..3f69d3c9c 100644
--- a/crates/codecs/src/codecs/webp.rs
+++ b/crates/codecs/src/codecs/webp.rs
@@ -128,9 +128,8 @@ pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result<Ve
enc.set_icc_profile(icc.clone());
}
if opts.embed_metadata {
- if let Some(exif) = &img.meta.exif {
- // The pixels are written as they are shown: never let a viewer rotate them again.
- enc.set_exif_metadata(crate::resolution::export_exif(exif, img.meta.dpi).into_owned());
+ if let Some(exif) = export_exif(&img) {
+ enc.set_exif_metadata(exif);
}
if let Some(xmp) = &img.meta.xmp {
enc.set_xmp_metadata(crate::resolution::export_xmp(xmp, img.meta.dpi).as_bytes().to_vec());
@@ -162,11 +161,40 @@ fn encode_lossy(img: &Image, opts: &EncodeOptions) -> Result<Vec<u8>, CodecError
None
};
let icc = if opts.embed_icc { img.icc.as_deref() } else { None };
- let exif = if opts.embed_metadata { img.meta.exif.as_deref().map(|e| crate::resolution::export_exif(e, img.meta.dpi)) } else { None };
+ let exif = if opts.embed_metadata { export_exif(img) } else { None };
let xmp = if opts.embed_metadata { img.meta.xmp.as_deref().map(|x| crate::resolution::export_xmp(x, img.meta.dpi)) } else { None };
Ok(riff(w, h, &frame, alpha.as_deref(), icc, exif.as_deref(), xmp.as_deref().map(str::as_bytes)))
}
+/// The EXIF to write: the image's, upright (the pixels are written as they are shown, so a viewer
+/// must never rotate them again), carrying the resolution. WebP has no resolution field of its own,
+/// so the resolution goes into EXIF, added when the image has none (#2399).
+pub(crate) fn export_exif(img: &Image) -> Option<Vec<u8>> {
+ let exif = img.meta.exif.as_deref().unwrap_or_default();
+ // A WebP without EXIF already reads as 72 ppi, so the default needs no block of its own (and
+ // the extended container it would bring to every web export).
+ if exif.is_empty() && img.meta.dpi.is_none_or(is_default_ppi) {
+ return None;
+ }
+ let out = crate::resolution::export_exif_adding_missing_resolution(exif, img.meta.dpi).into_owned();
+ (!out.is_empty()).then_some(out)
+}
+
+/// Whether a WebP of `img` keeps its resolution: the EXIF written carries it. Not when the image's
+/// own EXIF can't be parsed: that block is written as it is rather than replaced, so the
+/// resolution is dropped (and reported) instead of the metadata.
+pub(crate) fn keeps_dpi(img: &Image) -> bool {
+ let bare_default = img.meta.exif.as_deref().is_none_or(<[u8]>::is_empty) && img.meta.dpi.is_none_or(is_default_ppi);
+ // The XMP written beside it carries the resolution too, and readers look there first.
+ let in_xmp = img.meta.xmp.as_deref().is_some_and(|x| crate::resolution::xmp_resolution(&crate::resolution::export_xmp(x, img.meta.dpi)).is_some());
+ bare_default || in_xmp || export_exif(img).is_some_and(|e| crate::resolution::exif_resolution(&e).is_some())
+}
+
+/// 72 ppi each way: what a file without a resolution opens as.
+fn is_default_ppi((x, y): (f32, f32)) -> bool {
+ (x - 72.0).abs() < 0.01 && (y - 72.0).abs() < 0.01
+}
+
/// A RIFF chunk: FourCC, little-endian size, payload, padded to an even length.
fn chunk(out: &mut Vec<u8>, fourcc: &[u8; 4], payload: &[u8]) {
out.extend_from_slice(fourcc);
diff --git a/crates/codecs/src/fidelity.rs b/crates/codecs/src/fidelity.rs
index d80bb9ef7..c9bce9671 100644
--- a/crates/codecs/src/fidelity.rs
+++ b/crates/codecs/src/fidelity.rs
@@ -268,7 +268,7 @@ pub fn fidelity_warnings_with(image: &Image, format: Format, opts: &EncodeOption
w.push(W::MetadataTooLarge { what: "XMP", bytes: xmp.len() });
}
}
- if m.dpi.is_some() && !c.dpi {
+ if m.dpi.is_some() && (!c.dpi || (format == Format::WebP && !crate::codecs::webp::keeps_dpi(image))) {
w.push(W::DpiDropped);
}
// DPX keeps its own header fields, not free-form text.
diff --git a/crates/codecs/src/format.rs b/crates/codecs/src/format.rs
index a602da57b..a333106ab 100644
--- a/crates/codecs/src/format.rs
+++ b/crates/codecs/src/format.rs
@@ -256,7 +256,8 @@ pub fn caps(format: Format) -> FormatCaps {
}
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: TIFF_LAYOUTS, icc: true, exif: true, xmp: true, dpi: true, text: true, ..base },
- Format::WebP => FormatCaps { icc: true, exif: true, xmp: true, animation: true, ..base },
+ // Resolution travels in EXIF (WebP has no field of its own).
+ Format::WebP => FormatCaps { icc: true, exif: true, xmp: true, dpi: true, animation: true, ..base },
Format::Gif => FormatCaps { layouts: &[L::Rgba], animation: true, lossy: true, ..base },
Format::Bmp => base,
Format::Tga => FormatCaps { layouts: RGB_GRAY, ..base },
diff --git a/crates/codecs/tests/it/fidelity.rs b/crates/codecs/tests/it/fidelity.rs
index 2cdaf20c5..fa77a8d47 100644
--- a/crates/codecs/tests/it/fidelity.rs
+++ b/crates/codecs/tests/it/fidelity.rs
@@ -99,13 +99,14 @@ fn exif_xmp_dpi_text_dropped_for_qoi() {
assert!(w.contains(&x), "{x:?}");
}
}
+/// WebP keeps the resolution in EXIF (#2399); only free-form text has nowhere to go.
#[test]
-fn webp_drops_dpi_and_text_only() {
+fn webp_drops_text_only() {
let mut img = test_image(ChannelLayout::Rgb, SampleType::U8);
img.meta =
Metadata { exif: Some(sample_exif()), xmp: Some("x".into()), dpi: Some((72.0, 72.0)), text: vec![("a".into(), "b".into())], ..Default::default() };
let w = warns(&img, Format::WebP);
- assert_eq!(w, vec![W::DpiDropped, W::TextDropped]);
+ assert_eq!(w, vec![W::TextDropped]);
}
#[test]
fn float_to_png_reduces_and_clips() {
diff --git a/crates/codecs/tests/it/metadata.rs b/crates/codecs/tests/it/metadata.rs
index b33ae0a71..f84ec6336 100644
--- a/crates/codecs/tests/it/metadata.rs
+++ b/crates/codecs/tests/it/metadata.rs
@@ -38,6 +38,12 @@ fn check_format(format: Format) {
// TIFF writes the block's directories as its own and rebuilds a block from them on
// reading (tests/it/tiff_exif.rs); IFD0's orientation here is the image's.
assert!(!warnings.contains(&FidelityWarning::ExifDropped), "{format:?}");
+ } else if c.exif && format == Format::WebP {
+ // WebP's resolution lives in EXIF, so the block comes back with resolution tags added.
+ let back_exif = back.meta.exif.as_deref().unwrap_or_else(|| panic!("{format:?} lost exif"));
+ assert_eq!(photocraft_codecs::resolution::exif_resolution(back_exif).map(|(x, y)| (x.round(), y.round())), Some((300.0, 150.0)));
+ // The rest of the block survives too: the Orientation tag (0x0112, little-endian).
+ assert!(back_exif.windows(2).any(|w| w == b"\x12\x01"), "{format:?} lost Orientation");
} else if c.exif {
assert_eq!(back.meta.exif, img.meta.exif, "{format:?} exif");
} else {
@@ -295,3 +301,40 @@ fn metadata_survives_depth_conversion() {
assert_eq!(back.icc, img.icc);
assert_eq!(back.meta.xmp, img.meta.xmp);
}
+
+/// #2399: a WebP export keeps the resolution even when the image has no EXIF (WebP has no
+/// resolution field of its own, so a minimal EXIF block carries it), lossless and lossy alike,
+/// and no longer warns that it is dropped.
+#[test]
+fn webp_keeps_dpi_without_source_exif() {
+ let mut img = test_image(ChannelLayout::Rgb, SampleType::U8);
+ img.meta = Metadata { dpi: Some((300.0, 150.0)), ..Default::default() };
+ assert!(!fidelity_warnings(&img, Format::WebP).contains(&FidelityWarning::DpiDropped));
+ for lossless in [true, false] {
+ let opts = EncodeOptions { webp_lossless: lossless, ..Default::default() };
+ let back = decode(&encode(&img, Format::WebP, &opts).unwrap()).unwrap();
+ let (x, y) = back.meta.dpi.unwrap_or_else(|| panic!("lossless {lossless}: dpi lost"));
+ assert!((x - 300.0).abs() < 0.05 && (y - 150.0).abs() < 0.05, "lossless {lossless}: {x},{y}");
+ }
+ // EXIF that can't be parsed is written as it is, so the resolution is reported as dropped.
+ img.meta = Metadata { exif: Some(b"Exif\0\0garbage".to_vec()), dpi: Some((300.0, 150.0)), ..Default::default() };
+ assert!(fidelity_warnings(&img, Format::WebP).contains(&FidelityWarning::DpiDropped));
+ let back = decode(&encode(&img, Format::WebP, &EncodeOptions::default()).unwrap()).unwrap();
+ assert!(back.meta.exif.is_some());
+ // ...unless the XMP written beside it records the resolution, which readers look at first.
+ img.meta.xmp = Some(r#"<x:xmpmeta><rdf:Description tiff:XResolution="300/1" tiff:YResolution="150/1" tiff:ResolutionUnit="2"/></x:xmpmeta>"#.into());
+ assert!(!fidelity_warnings(&img, Format::WebP).contains(&FidelityWarning::DpiDropped));
+ let back = decode(&encode(&img, Format::WebP, &EncodeOptions::default()).unwrap()).unwrap();
+ let (x, y) = back.meta.dpi.expect("dpi from XMP");
+ assert!((x - 300.0).abs() < 0.05 && (y - 150.0).abs() < 0.05, "{x},{y}");
+ // The default 72 ppi needs no EXIF (a WebP without one opens at 72), so a plain export stays
+ // a simple-format file; nor does an image without a resolution.
+ img.meta = Metadata { dpi: Some((72.0, 72.0)), ..Default::default() };
+ assert!(!fidelity_warnings(&img, Format::WebP).contains(&FidelityWarning::DpiDropped));
+ let bytes = encode(&img, Format::WebP, &EncodeOptions { webp_lossless: false, ..Default::default() }).unwrap();
+ assert_eq!(bytes.get(12..16), Some(&b"VP8 "[..]));
+ // Without a resolution or EXIF there is still no EXIF chunk.
+ img.meta = Metadata::default();
+ let back = decode(&encode(&img, Format::WebP, &EncodeOptions::default()).unwrap()).unwrap();
+ assert!(back.meta.exif.is_none());
+}