Skip to content

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

Save for Web and Quick Export: "All" keeps the photo's EXIF (fixes #7436) (#7471)

Marco Arnulfo0eb0387d5344
diff --git a/crates/codecs/src/web.rs b/crates/codecs/src/web.rs
index 584ceb9d6..dfd0cd9b9 100644
--- a/crates/codecs/src/web.rs
+++ b/crates/codecs/src/web.rs
@@ -285,7 +285,8 @@ pub fn decode_wbmp(bytes: &[u8]) -> Result<(u32, u32, Vec<bool>), CodecError> {
}
/// JPEG from 8-bit RGB (`rgb.len() == 3·w·h`): quality 1..=100, optional progressive scans and
-/// optimised Huffman tables (Save for Web's "Optimized"), optional ICC profile, density and XMP.
+/// optimised Huffman tables (Save for Web's "Optimized"), optional ICC profile, density, EXIF and
+/// XMP. EXIF that doesn't fit in one segment is left out (see [`jpeg_exif_fits`]).
#[allow(clippy::too_many_arguments)]
pub fn encode_jpeg_rgb8(
width: u32,
@@ -296,6 +297,7 @@ pub fn encode_jpeg_rgb8(
optimized: bool,
icc: Option<&[u8]>,
dpi: Option<f32>,
+ exif: Option<&[u8]>,
xmp: Option<&str>,
) -> Result<Vec<u8>, CodecError> {
let e = |e: jpeg_encoder::EncodingError| CodecError::encode(Format::Jpeg, e);
@@ -319,9 +321,14 @@ pub fn encode_jpeg_rgb8(
let v = d.round().min(65535.0) as u16;
enc.set_density(jpeg_encoder::Density::Inch { x: v, y: v });
}
+ let ppi = dpi.filter(|d| *d >= 1.0).map(|d| (d, d));
+ // Upright, without the source's thumbnail, at the JFIF resolution, as Save As writes it.
+ if let Some(seg) = exif.and_then(|x| crate::codecs::jpeg::exif_segment(x, ppi)) {
+ enc.add_app_segment(1, &seg).map_err(e)?;
+ }
if let Some(x) = xmp {
// Its `tiff:` resolution, if any, says what the JFIF density says (#1691).
- let x = crate::resolution::export_xmp(x, dpi.filter(|d| *d >= 1.0).map(|d| (d, d)));
+ let x = crate::resolution::export_xmp(x, ppi);
let mut seg = b"http://ns.adobe.com/xap/1.0/\0".to_vec();
seg.extend_from_slice(x.as_bytes());
enc.add_app_segment(1, &seg).map_err(e)?;
@@ -333,6 +340,11 @@ pub fn encode_jpeg_rgb8(
Ok(out)
}
+/// Whether [`encode_jpeg_rgb8`] can write `exif` at `dpi` (it must fit in one APP1 segment).
+pub fn jpeg_exif_fits(exif: &[u8], dpi: Option<f32>) -> bool {
+ crate::codecs::jpeg::exif_segment(exif, dpi.filter(|d| *d >= 1.0).map(|d| (d, d))).is_some()
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -359,7 +371,7 @@ mod tests {
let rgb: Vec<u8> = (0..16 * 16 * 3).map(|i| (i * 37 % 256) as u8).collect();
for (q, want) in [(1, (2, 2)), (50, (2, 2)), (51, (1, 1)), (60, (1, 1)), (89, (1, 1)), (100, (1, 1))] {
for progressive in [false, true] {
- let bytes = encode_jpeg_rgb8(16, 16, &rgb, q, progressive, false, None, None, None).unwrap();
+ let bytes = encode_jpeg_rgb8(16, 16, &rgb, q, progressive, false, None, None, None, None).unwrap();
assert_eq!(luma_sampling(&bytes), Some(want), "quality {q} progressive {progressive}");
}
}
@@ -428,8 +440,8 @@ mod tests {
#[test]
fn progressive_jpeg_decodes() {
let rgb: Vec<u8> = (0..64 * 48 * 3).map(|i| (i % 251) as u8).collect();
- let base = encode_jpeg_rgb8(64, 48, &rgb, 80, false, false, None, Some(72.0), Some("<x:xmpmeta/>")).unwrap();
- let prog = encode_jpeg_rgb8(64, 48, &rgb, 80, true, true, None, None, None).unwrap();
+ let base = encode_jpeg_rgb8(64, 48, &rgb, 80, false, false, None, Some(72.0), None, Some("<x:xmpmeta/>")).unwrap();
+ let prog = encode_jpeg_rgb8(64, 48, &rgb, 80, true, true, None, None, None, None).unwrap();
assert_ne!(base, prog);
assert_eq!(crate::decode(&base).unwrap().meta.xmp.as_deref(), Some("<x:xmpmeta/>"));
// SOF2 marks a progressive frame.
@@ -442,7 +454,7 @@ mod tests {
fn web_jpeg_xmp_resolution_follows_the_density() {
let rgb = vec![100u8; 8 * 8 * 3];
let xmp = r#"<rdf:Description tiff:XResolution="300/1" tiff:YResolution="300/1"/>"#;
- let out = encode_jpeg_rgb8(8, 8, &rgb, 80, false, false, None, Some(72.0), Some(xmp)).unwrap();
+ let out = encode_jpeg_rgb8(8, 8, &rgb, 80, false, false, None, Some(72.0), None, Some(xmp)).unwrap();
let img = crate::decode(&out).unwrap();
assert_eq!(img.meta.dpi, Some((72.0, 72.0)));
assert_eq!(img.meta.xmp.as_deref().and_then(crate::xmp_resolution), Some((72.0, 72.0)));
@@ -461,7 +473,7 @@ mod subsampling_tests {
let rgb: Vec<u8> = (0..w * h).flat_map(|i| [((i % w) * 4) as u8, 76, ((i / w) * 5) as u8]).collect();
for q in [30, 60, 95] {
for (prog, opt) in [(false, false), (false, true), (true, false), (true, true)] {
- let bytes = encode_jpeg_rgb8(w, h, &rgb, q, prog, opt, None, None, None).unwrap();
+ let bytes = encode_jpeg_rgb8(w, h, &rgb, q, prog, opt, None, None, None, None).unwrap();
let ours = crate::decode(&bytes).unwrap().convert(crate::ChannelLayout::Rgb, crate::SampleType::U8);
let err = ours.data().iter().zip(&rgb).map(|(a, b)| i32::from(*a).abs_diff(i32::from(*b))).max().unwrap();
assert!(err < 24, "q{q} progressive={prog} optimized={opt}: max error {err}");
diff --git a/crates/engine/examples/bench_web_palette.rs b/crates/engine/examples/bench_web_palette.rs
index 5ed1c3a3b..4b8b87616 100644
--- a/crates/engine/examples/bench_web_palette.rs
+++ b/crates/engine/examples/bench_web_palette.rs
@@ -18,13 +18,13 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let settings = WebSettings::from_params(&json!({"format": "gif", "colors": 128, "dither": "diffusion"}), "bench")?;
let rect = Rect::new(0, 0, w as i32, h as i32);
let started = Instant::now();
- let original = optimize(&pixels, w, rect, &settings, None, None, 72.0, false)?;
+ let original = optimize(&pixels, w, rect, &settings, None, None, None, 72.0, false)?;
println!("24 MP generated palette: {:.1} ms", started.elapsed().as_secs_f64() * 1000.0);
let mut edited = settings;
edited.color_table = Some(original.color_table);
edited.color_table_edits.insert(0, [0, 255, 0]);
let started = Instant::now();
- let result = optimize(&pixels, w, rect, &edited, None, None, 72.0, false)?;
+ let result = optimize(&pixels, w, rect, &edited, None, None, None, 72.0, false)?;
println!("24 MP edited fixed palette: {:.1} ms ({} bytes)", started.elapsed().as_secs_f64() * 1000.0, result.bytes.len());
Ok(())
}
diff --git a/crates/engine/src/web_cmds.rs b/crates/engine/src/web_cmds.rs
index 9f0e25574..29237fd5a 100644
--- a/crates/engine/src/web_cmds.rs
+++ b/crates/engine/src/web_cmds.rs
@@ -70,6 +70,9 @@ pub enum WebMetadata {
None,
Copyright,
CopyrightAndContact,
+ /// All the XMP, none of the photo's EXIF (camera, date taken, GPS).
+ AllExceptCameraInfo,
+ /// All the XMP and the photo's EXIF.
All,
}
@@ -203,8 +206,9 @@ impl WebSettings {
"none" => WebMetadata::None,
"copyright" => WebMetadata::Copyright,
"copyrightAndContact" | "contact" => WebMetadata::CopyrightAndContact,
- "all" | "allExceptCameraInfo" => WebMetadata::All,
- m => return Err(bad(cmd, format!("unknown metadata `{m}` (none|copyright|copyrightAndContact|all)"))),
+ "allExceptCameraInfo" => WebMetadata::AllExceptCameraInfo,
+ "all" => WebMetadata::All,
+ m => return Err(bad(cmd, format!("unknown metadata `{m}` (none|copyright|copyrightAndContact|allExceptCameraInfo|all)"))),
};
}
if let Some(table) = p.get("colorTable") {
@@ -262,6 +266,7 @@ impl WebSettings {
WebMetadata::None => "none",
WebMetadata::Copyright => "copyright",
WebMetadata::CopyrightAndContact => "copyrightAndContact",
+ WebMetadata::AllExceptCameraInfo => "allExceptCameraInfo",
WebMetadata::All => "all",
};
let matte = self.matte.map_or("none".to_string(), |c| format!("#{:02x}{:02x}{:02x}", to8(c[0]), to8(c[1]), to8(c[2])));
@@ -387,7 +392,7 @@ pub fn web_xmp(doc: &Document, m: WebMetadata) -> Option<String> {
let xmp = doc.metadata.xmp.as_deref()?;
match m {
WebMetadata::None => None,
- WebMetadata::All => Some(xmp.to_string()),
+ WebMetadata::All | WebMetadata::AllExceptCameraInfo => Some(xmp.to_string()),
WebMetadata::Copyright | WebMetadata::CopyrightAndContact => {
let info = crate::file_cmds::read_file_info(Some(xmp));
let mut keep = serde_json::Map::new();
@@ -405,10 +410,33 @@ pub fn web_xmp(doc: &Document, m: WebMetadata) -> Option<String> {
}
}
+/// The photo's EXIF to embed for the metadata choice: only "All" carries it (#7436).
+pub fn web_exif(doc: &Document, m: WebMetadata) -> Option<&[u8]> {
+ doc.metadata.exif.as_deref().map(Vec::as_slice).filter(|_| m == WebMetadata::All)
+}
+
+/// The response's warnings: EXIF that a JPEG couldn't hold (one segment, about 64 KB).
+fn web_warnings(st: &WebSettings, exif: Option<&[u8]>, dpi: f32) -> Vec<String> {
+ exif.filter(|x| st.format == WebFormat::Jpeg && !photocraft_codecs::web::jpeg_exif_fits(x, Some(dpi)))
+ .map(|x| photocraft_codecs::FidelityWarning::MetadataTooLarge { what: "EXIF", bytes: x.len() }.to_string())
+ .into_iter()
+ .collect()
+}
+
/// Optimises `rect` of `px` (straight RGBA, `bw` wide) with `st`. `preview` also returns what
/// the file looks like (the dialog's panes); exports skip it.
#[allow(clippy::too_many_arguments)]
-pub fn optimize(px: &[[f32; 4]], bw: usize, rect: Rect, st: &WebSettings, icc: Option<&[u8]>, xmp: Option<&str>, dpi: f32, preview: bool) -> Result<Optimized> {
+pub fn optimize(
+ px: &[[f32; 4]],
+ bw: usize,
+ rect: Rect,
+ st: &WebSettings,
+ icc: Option<&[u8]>,
+ exif: Option<&[u8]>,
+ xmp: Option<&str>,
+ dpi: f32,
+ preview: bool,
+) -> Result<Optimized> {
if bw == 0 || rect.x0 < 0 || rect.y0 < 0 || rect.is_empty() || rect.x1 as usize > bw || (rect.y1 as usize).checked_mul(bw).is_none_or(|end| end > px.len())
{
return Err(other("slice is outside the pixel buffer"));
@@ -460,8 +488,9 @@ pub fn optimize(px: &[[f32; 4]], bw: usize, rect: Rect, st: &WebSettings, icc: O
}
// Save for Web's 0–100 quality → encoder 1–100.
let q = st.quality.max(1);
- let bytes = photocraft_codecs::web::encode_jpeg_rgb8(ww, hh, &rgb, q, st.progressive, st.optimized, icc.filter(|_| st.embed_icc), Some(dpi), xmp)
- .map_err(e)?;
+ let bytes =
+ photocraft_codecs::web::encode_jpeg_rgb8(ww, hh, &rgb, q, st.progressive, st.optimized, icc.filter(|_| st.embed_icc), Some(dpi), exif, xmp)
+ .map_err(e)?;
if preview {
// The preview shows the compression artefacts.
look = match photocraft_codecs::decode(&bytes) {
@@ -873,7 +902,9 @@ fn save_for_web_impl(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u
let bw = wdoc.size.width as usize;
let icc = wdoc.icc_profile.as_deref().map(|v| v.as_slice());
let xmp = web_xmp(&doc, st.metadata);
+ let exif = web_exif(&doc, st.metadata);
let dpi = wdoc.resolution_dpi;
+ let warnings = web_warnings(&st, exif, dpi);
let all = slices::resolve(&doc);
let pick = p.get("slices").and_then(Value::as_str).unwrap_or("all");
let numbers: Option<Vec<u64>> = p.get("numbers").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).collect());
@@ -895,18 +926,18 @@ fn save_for_web_impl(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u
}
// Estimate only (the dialog's annotations): the whole image, or each chosen slice.
if single.is_none() && dir.is_none() {
- let o = optimize(&buf.px, bw, wdoc.bounds(), &st, icc, xmp.as_deref(), dpi, false)?;
+ let o = optimize(&buf.px, bw, wdoc.bounds(), &st, icc, exif, xmp.as_deref(), dpi, false)?;
return Ok(
json!({"format": o.ext, "bytes": o.bytes.len(), "width": o.width, "height": o.height, "colors": o.colors, "colorTable": o.color_table.iter().map(|c| rgb_hex(*c)).collect::<Vec<_>>(), "transparentIndex": o.transparent_index}),
);
}
if let Some(path) = single.filter(|_| dir.is_none() && (all.len() == 1 || p.get("slices").is_none())) {
- let o = optimize(&buf.px, bw, wdoc.bounds(), &st, icc, xmp.as_deref(), dpi, false)?;
+ let o = optimize(&buf.px, bw, wdoc.bounds(), &st, icc, exif, xmp.as_deref(), dpi, false)?;
write(path, &o.bytes)?;
remember_web_settings(s, cmd, &last_web);
s.file_menu.last_web = Some(last_web);
crate::automate_cmds::fire_event(s, "export");
- return Ok(json!({"files": [path], "bytes": o.bytes.len(), "width": o.width, "height": o.height, "colors": o.colors}));
+ return Ok(json!({"files": [path], "bytes": o.bytes.len(), "width": o.width, "height": o.height, "colors": o.colors, "warnings": warnings}));
}
let dir =
dir.map(str::to_string).or_else(|| single.and_then(|f| std::path::Path::new(f).parent().map(|d| d.to_string_lossy().into_owned()))).unwrap_or_default();
@@ -961,7 +992,7 @@ fn save_for_web_impl(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u
cells.push((piece, bg, text));
continue;
}
- let o = optimize(&buf.px, bw, piece, &st, icc, xmp.as_deref(), dpi, false)?;
+ let o = optimize(&buf.px, bw, piece, &st, icc, exif, xmp.as_deref(), dpi, false)?;
let stem = if split { format!("{}_{:02}", slice_file(&r.name), k + 1) } else { slice_file(&r.name) };
let name = unique(&stem, o.ext);
let rel = if images.is_empty() { name.clone() } else { format!("{images}/{name}") };
@@ -997,7 +1028,9 @@ fn save_for_web_impl(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u
remember_web_settings(s, cmd, &last_web);
s.file_menu.last_web = Some(last_web);
crate::automate_cmds::fire_event(s, "export");
- Ok(json!({"files": files, "html": html_path, "bytes": total, "slices": chosen.len(), "width": wdoc.size.width, "height": wdoc.size.height}))
+ Ok(
+ json!({"files": files, "html": html_path, "bytes": total, "slices": chosen.len(), "width": wdoc.size.width, "height": wdoc.size.height, "warnings": warnings}),
+ )
}
// ---------- Export Preferences / Quick Export ----------
@@ -1108,19 +1141,21 @@ fn quick_export(s: &mut Session, p: &Value) -> Result<Value> {
let (wdoc, _, _) = web_document(&doc, &json!({}), &st)?;
let buf = photocraft_compose::flatten(&wdoc);
let xmp = web_xmp(&doc, st.metadata);
+ let exif = web_exif(&doc, st.metadata);
let opt = optimize(
&buf.px,
wdoc.size.width as usize,
wdoc.bounds(),
&st,
wdoc.icc_profile.as_deref().map(|v| v.as_slice()),
+ exif,
xmp.as_deref(),
wdoc.resolution_dpi,
false,
)?;
write_file(&path, &opt.bytes)?;
crate::automate_cmds::fire_event(s, "export");
- Ok(json!({"path": path, "format": fmt, "bytes": opt.bytes.len()}))
+ Ok(json!({"path": path, "format": fmt, "bytes": opt.bytes.len(), "warnings": web_warnings(&st, exif, wdoc.resolution_dpi)}))
}
// ---------- Generate › Image Assets ----------
@@ -1430,7 +1465,7 @@ pub fn generate_assets(doc: &Document, dir: &str) -> (Vec<String>, Vec<Value>) {
return Ok(reported);
}
let buf = photocraft_compose::flatten(&wdoc);
- let o = optimize(&buf.px, wdoc.size.width as usize, wdoc.bounds(), &st, None, None, wdoc.resolution_dpi, false)?;
+ let o = optimize(&buf.px, wdoc.size.width as usize, wdoc.bounds(), &st, None, None, None, wdoc.resolution_dpi, false)?;
let (out, reported) = asset_output_path(dir, &rel)?;
write_file(&out, &o.bytes)?;
written.insert(key);
@@ -1504,7 +1539,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Save for Web (Legacy)…",
&["File", "Export"],
Some("Cmd+Alt+Shift+S"),
- r##"{"preset":"GIF 128 Dithered|JPEG High|PNG-24|…"?,"format":"gif|png8|png24|jpeg|wbmp"="png24","palette":"perceptual|selective|adaptive|restrictive|exact|systemMac|systemWindows|uniform"="selective","colors":2..256=256,"colorTable":["#rrggbb",…]? (fixed opaque source palette, 1–256 entries; 255 with transparency),"colorTableEdits":{"0":"#rrggbb",…}? (replace entries after indexing; requires colorTable),"dither":"none|diffusion|pattern|noise"="diffusion","ditherAmount":0..100=88,"transparency":bool=true,"matte":"#rrggbb|none"="none" (a preset's own: white; formats without transparency go over white),"interlaced":bool=false,"webSnap":0..100=0,"quality":0..100=60,"progressive":bool=false,"optimized":bool=true,"embedIcc":bool=false,"metadata":"none|copyright|copyrightAndContact|all"="copyright","convertToSrgb":bool=true,"width"|"height"|"percent"? (image size),"resample":"bicubic|bilinear|nearest"?,"path":file? (whole image),"dir":folder? (one file per slice in images/),"imagesFolder":relative-folder?="images","html":bool=false,"trustedSliceHtml":bool=false (only for trusted documents; emit raw no-image cell HTML),"slices":"all|user"="all","numbers":[n]?} → no path/dir: {bytes,width,height,colors,colorTable,transparentIndex} estimate; else {files, html, bytes}"##,
+ r##"{"preset":"GIF 128 Dithered|JPEG High|PNG-24|…"?,"format":"gif|png8|png24|jpeg|wbmp"="png24","palette":"perceptual|selective|adaptive|restrictive|exact|systemMac|systemWindows|uniform"="selective","colors":2..256=256,"colorTable":["#rrggbb",…]? (fixed opaque source palette, 1–256 entries; 255 with transparency),"colorTableEdits":{"0":"#rrggbb",…}? (replace entries after indexing; requires colorTable),"dither":"none|diffusion|pattern|noise"="diffusion","ditherAmount":0..100=88,"transparency":bool=true,"matte":"#rrggbb|none"="none" (a preset's own: white; formats without transparency go over white),"interlaced":bool=false,"webSnap":0..100=0,"quality":0..100=60,"progressive":bool=false,"optimized":bool=true,"embedIcc":bool=false,"metadata":"none|copyright|copyrightAndContact|allExceptCameraInfo|all"="copyright" (EXIF only with all),"convertToSrgb":bool=true,"width"|"height"|"percent"? (image size),"resample":"bicubic|bilinear|nearest"?,"path":file? (whole image),"dir":folder? (one file per slice in images/),"imagesFolder":relative-folder?="images","html":bool=false,"trustedSliceHtml":bool=false (only for trusted documents; emit raw no-image cell HTML),"slices":"all|user"="all","numbers":[n]?} → no path/dir: {bytes,width,height,colors,colorTable,transparentIndex} estimate; else {files, html, bytes, warnings}"##,
has_doc,
save_for_web
),
@@ -1522,7 +1557,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Quick Export",
&[],
None,
- r##"{"path":str? (required unless Export Preferences › Location is "sameFolder" and the document is saved)} → {path, format, bytes}"##,
+ r##"{"path":str? (required unless Export Preferences › Location is "sameFolder" and the document is saved)} → {path, format, bytes, warnings}"##,
native_doc,
quick_export
),
diff --git a/crates/engine/src/web_cmds/color_table_tests.rs b/crates/engine/src/web_cmds/color_table_tests.rs
index 1d319cb38..0c25ce0d2 100644
--- a/crates/engine/src/web_cmds/color_table_tests.rs
+++ b/crates/engine/src/web_cmds/color_table_tests.rs
@@ -7,13 +7,13 @@ fn color_replacement_preserves_pixel_membership_and_transparency() {
for dither in ["none", "diffusion", "pattern", "noise"] {
let p = json!({"format": format, "colorTable": ["#ff0000", "#0000ff"], "dither": dither, "matte": "none"});
let original = WebSettings::from_params(&p, "test").unwrap();
- let before = optimize(&px, 4, Rect::new(0, 0, 4, 1), &original, None, None, 72.0, true).unwrap();
+ let before = optimize(&px, 4, Rect::new(0, 0, 4, 1), &original, None, None, None, 72.0, true).unwrap();
let mut edited = p.clone();
// Replace red with blue: re-quantization would now send all opaque pixels to blue.
edited["colorTableEdits"] = json!({"0": "#0000ff", "1": "#00ff00"});
let settings = WebSettings::from_params(&edited, "test").unwrap();
assert_eq!(WebSettings::from_params(&settings.to_params(), "test").unwrap(), settings);
- let after = optimize(&px, 4, Rect::new(0, 0, 4, 1), &settings, None, None, 72.0, true).unwrap();
+ let after = optimize(&px, 4, Rect::new(0, 0, 4, 1), &settings, None, None, None, 72.0, true).unwrap();
for (old, new) in before.preview.as_chunks::<4>().0.iter().zip(after.preview.as_chunks::<4>().0) {
if old[3] == 0 {
assert_eq!(new[3], 0);
@@ -81,8 +81,8 @@ fn malformed_tables_and_out_of_bounds_slices_return_errors() {
}
let settings = WebSettings::default();
for (bw, rect) in [(0, Rect::new(0, 0, 1, 1)), (1, Rect::new(-1, 0, 1, 1)), (1, Rect::new(0, 0, 2, 1)), (1, Rect::new(0, 0, 1, i32::MAX))] {
- assert!(optimize(&[[0.0; 4]], bw, rect, &settings, None, None, 72.0, false).is_err());
+ assert!(optimize(&[[0.0; 4]], bw, rect, &settings, None, None, None, 72.0, false).is_err());
}
let settings = WebSettings::from_params(&json!({"format": "gif", "colorTable": vec!["#000000"; 256]}), "test").unwrap();
- assert!(optimize(&[[0.0; 4]], 1, Rect::new(0, 0, 1, 1), &settings, None, None, 72.0, true).is_err());
+ assert!(optimize(&[[0.0; 4]], 1, Rect::new(0, 0, 1, 1), &settings, None, None, None, 72.0, true).is_err());
}
diff --git a/crates/engine/src/web_cmds/tests.rs b/crates/engine/src/web_cmds/tests.rs
index bd55a549c..5791e5f27 100644
--- a/crates/engine/src/web_cmds/tests.rs
+++ b/crates/engine/src/web_cmds/tests.rs
@@ -735,7 +735,7 @@ fn previews_show_the_optimised_pixels() {
let buf = photocraft_compose::flatten(&wd);
for f in ["jpeg", "gif", "png8", "png24", "wbmp"] {
let st = WebSettings::from_params(&json!({"format": f, "quality": 90, "transparency": false}), "x").unwrap();
- let o = optimize(&buf.px, 64, wd.bounds(), &st, None, None, 72.0, true).unwrap();
+ let o = optimize(&buf.px, 64, wd.bounds(), &st, None, None, None, 72.0, true).unwrap();
assert_eq!(o.preview.len(), 64 * 48 * 4, "{f}");
// Red square centre stays red (WBMP: dark).
let i = (16 * 64 + 16) * 4;
@@ -745,7 +745,7 @@ fn previews_show_the_optimised_pixels() {
} else {
assert!(px[0] > 200 && px[1] < 60 && px[2] < 60, "{f}: {px:?}");
}
- let none = optimize(&buf.px, 64, wd.bounds(), &st, None, None, 72.0, false).unwrap();
+ let none = optimize(&buf.px, 64, wd.bounds(), &st, None, None, None, 72.0, false).unwrap();
assert!(none.preview.is_empty());
assert_eq!(none.bytes, o.bytes);
}
@@ -756,7 +756,7 @@ fn jpeg_preview_at_odd_sizes() {
for (w, h, q) in [(640usize, 431usize, 90), (640, 430, 60), (333, 222, 30)] {
let px: Vec<[f32; 4]> = (0..w * h).map(|i| [((i % w) as f32 / w as f32), 0.3, ((i / w) as f32 / h as f32), 1.0]).collect();
let st = WebSettings::from_params(&json!({"format": "jpeg", "quality": q}), "x").unwrap();
- let o = optimize(&px, w, Rect::new(0, 0, w as i32, h as i32), &st, None, None, 72.0, true).unwrap();
+ let o = optimize(&px, w, Rect::new(0, 0, w as i32, h as i32), &st, None, None, None, 72.0, true).unwrap();
for &(x, y) in &[(10usize, 10usize), (w - 10, h / 2), (w / 2, h - 5)] {
let i = (y * w + x) * 4;
let want = [(x as f32 / w as f32 * 255.0) as i32, 76, (y as f32 / h as f32 * 255.0) as i32];
@@ -814,3 +814,166 @@ fn overlapping_slices_keep_the_later_slice_in_html() {
#[path = "color_table_tests.rs"]
mod color_table_tests;
+
+/// A little-endian camera EXIF: IFD0 with Make, Orientation 6, 300 ppi and pointers to an Exif
+/// IFD (DateTimeOriginal) and a GPS IFD (GPSLatitudeRef); IFD0 links to an IFD1 thumbnail.
+fn camera_exif() -> Vec<u8> {
+ let entry = |v: &mut Vec<u8>, tag: u16, ty: u16, count: u32, value: u32| {
+ v.extend_from_slice(&tag.to_le_bytes());
+ v.extend_from_slice(&ty.to_le_bytes());
+ v.extend_from_slice(&count.to_le_bytes());
+ v.extend_from_slice(&value.to_le_bytes());
+ };
+ let (ifd0, data0) = (8u32, 8 + 2 + 7 * 12 + 4);
+ let (make, xres, yres) = (data0, data0 + 10, data0 + 18);
+ let exif_ifd = data0 + 26;
+ let date = exif_ifd + 2 + 12 + 4;
+ let gps_ifd = date + 20;
+ let ifd1 = gps_ifd + 2 + 12 + 4;
+ let mut v = b"II*\0".to_vec();
+ v.extend_from_slice(&ifd0.to_le_bytes());
+ v.extend_from_slice(&7u16.to_le_bytes());
+ entry(&mut v, 0x010F, 2, 9, make);
+ entry(&mut v, 0x0112, 3, 1, 6);
+ entry(&mut v, 282, 5, 1, xres);
+ entry(&mut v, 283, 5, 1, yres);
+ entry(&mut v, 296, 3, 1, 2);
+ entry(&mut v, 0x8769, 4, 1, exif_ifd);
+ entry(&mut v, 0x8825, 4, 1, gps_ifd);
+ v.extend_from_slice(&ifd1.to_le_bytes());
+ v.extend_from_slice(b"TestMake\0\0");
+ for _ in 0..2 {
+ v.extend_from_slice(&300u32.to_le_bytes());
+ v.extend_from_slice(&1u32.to_le_bytes());
+ }
+ v.extend_from_slice(&1u16.to_le_bytes());
+ entry(&mut v, 0x9003, 2, 20, date);
+ v.extend_from_slice(&0u32.to_le_bytes());
+ v.extend_from_slice(b"2024:05:01 10:30:00\0");
+ v.extend_from_slice(&1u16.to_le_bytes());
+ entry(&mut v, 0x0001, 2, 2, u32::from_le_bytes(*b"N\0\0\0"));
+ v.extend_from_slice(&0u32.to_le_bytes());
+ v.extend_from_slice(&1u16.to_le_bytes());
+ entry(&mut v, 0x0103, 3, 1, 6);
+ v.extend_from_slice(&0u32.to_le_bytes());
+ assert_eq!(v.len(), ifd1 as usize + 18);
+ v
+}
+
+/// The payload (after `Exif\0\0`) of the file's EXIF APP1 segment, read from the markers.
+fn exif_app1(bytes: &[u8]) -> Option<Vec<u8>> {
+ let mut i = 2;
+ while i + 4 <= bytes.len() && bytes[i] == 0xFF && bytes[i + 1] != 0xDA {
+ let len = u16::from_be_bytes([bytes[i + 2], bytes[i + 3]]) as usize;
+ let body = &bytes[i + 4..i + 2 + len];
+ if bytes[i + 1] == 0xE1 && body.starts_with(b"Exif\0\0") {
+ return Some(body[6..].to_vec());
+ }
+ i += 2 + len;
+ }
+ None
+}
+
+/// IFD0's entries (tag → inline value) and its link to the next IFD, little-endian only.
+fn ifd0(tiff: &[u8]) -> (std::collections::HashMap<u16, u32>, u32) {
+ let u16_at = |o: usize| u16::from_le_bytes([tiff[o], tiff[o + 1]]);
+ let u32_at = |o: usize| u32::from_le_bytes([tiff[o], tiff[o + 1], tiff[o + 2], tiff[o + 3]]);
+ assert_eq!(&tiff[..4], b"II*\0");
+ let at = u32_at(4) as usize;
+ let n = u16_at(at) as usize;
+ let tags = (0..n)
+ .map(|k| {
+ let e = at + 2 + k * 12;
+ let value = if u16_at(e + 2) == 3 { u32::from(u16_at(e + 8)) } else { u32_at(e + 8) };
+ (u16_at(e), value)
+ })
+ .collect();
+ (tags, u32_at(at + 2 + n * 12))
+}
+
+fn photo_session(exif: Vec<u8>) -> Session {
+ let mut s = session(8);
+ s.execute("file.fileInfo", json!({"copyright": "© Example"})).unwrap();
+ s.edit("exif", |doc, _| {
+ doc.metadata.exif = Some(std::sync::Arc::new(exif));
+ Ok(())
+ })
+ .unwrap();
+ s
+}
+
+/// #7436: Save for Web's "All" writes the photo's EXIF, as Save a Copy does: upright
+/// (Orientation 1), without the source's thumbnail and at the exported resolution. Every other
+/// choice, "All Except Camera Info" included, leaves the camera data (and GPS) out.
+#[test]
+fn save_for_web_all_writes_the_photos_exif() {
+ let dir = tmp("exif");
+ let mut s = photo_session(camera_exif());
+ let export = |s: &mut Session, metadata: &str| {
+ let path = format!("{dir}/{metadata}.jpg");
+ let r = s.execute("file.export.saveForWebLegacy", json!({"format": "jpeg", "metadata": metadata, "path": path})).unwrap();
+ (std::fs::read(&path).unwrap(), r)
+ };
+ let (all, r) = export(&mut s, "all");
+ let exif = exif_app1(&all).expect("an EXIF APP1 segment");
+ let camera = photocraft_algo::exif::read(&exif);
+ assert_eq!(camera.make.as_deref(), Some("TestMake"));
+ assert_eq!(camera.date_taken.as_deref(), Some("2024:05:01 10:30:00"));
+ let (tags, next) = ifd0(&exif);
+ assert_eq!(tags.get(&0x0112), Some(&1), "the exported pixels are already upright");
+ assert!(tags.contains_key(&0x8825), "GPS kept");
+ assert_eq!(next, 0, "the source's thumbnail is not linked");
+ assert_eq!(photocraft_codecs::exif_resolution(&exif), Some((72.0, 72.0)), "the document's resolution, not the source's 300");
+ assert!(decode(&format!("{dir}/all.jpg")).meta.xmp.unwrap_or_default().contains("Example"));
+ for m in ["none", "copyright", "copyrightAndContact", "allExceptCameraInfo"] {
+ let (bytes, r) = export(&mut s, m);
+ assert_eq!(exif_app1(&bytes), None, "{m}");
+ assert_eq!(r["warnings"], json!([]), "{m}");
+ }
+ assert_eq!(r["warnings"], json!([]), "it fits");
+ let xmp = decode(&format!("{dir}/allExceptCameraInfo.jpg")).meta.xmp.unwrap_or_default();
+ assert!(xmp.contains("Example"), "all the XMP");
+ assert_eq!(WebSettings::from_params(&json!({"metadata": "allExceptCameraInfo"}), "x").unwrap().to_params()["metadata"], "allExceptCameraInfo");
+}
+
+#[test]
+fn quick_export_all_writes_the_photos_exif() {
+ let dir = tmp("quick_exif");
+ let mut s = photo_session(camera_exif());
+ let export = |s: &mut Session, metadata: &str| {
+ s.execute("file.export.exportPreferences", json!({"quickExportFormat": "jpg", "metadata": metadata})).unwrap();
+ let path = format!("{dir}/{metadata}.jpg");
+ let r = s.execute("file.export.quickExport", json!({"path": path})).unwrap();
+ (std::fs::read(&path).unwrap(), r)
+ };
+ let (all, r) = export(&mut s, "all");
+ assert_eq!(photocraft_algo::exif::read(&exif_app1(&all).expect("EXIF")).make.as_deref(), Some("TestMake"));
+ assert_eq!(r["warnings"], json!([]));
+ assert_eq!(exif_app1(&export(&mut s, "copyright").0), None);
+ assert_eq!(exif_app1(&export(&mut s, "none").0), None);
+ s.execute("prefs.reset", json!({"path": "export"})).unwrap();
+}
+
+/// EXIF too large for its one segment is left out and said so; a truncated one doesn't panic.
+#[test]
+fn web_exif_that_does_not_fit_is_reported_and_bad_exif_is_harmless() {
+ let dir = tmp("exif_bad");
+ let mut big = camera_exif();
+ big.resize(70_000, 0);
+ let mut s = photo_session(big);
+ let path = format!("{dir}/big.jpg");
+ let r = s.execute("file.export.saveForWebLegacy", json!({"format": "jpeg", "metadata": "all", "path": path})).unwrap();
+ assert_eq!(exif_app1(&std::fs::read(&path).unwrap()), None);
+ assert!(r["warnings"][0].as_str().is_some_and(|w| w.contains("EXIF (70000 bytes)")), "{r}");
+ s.execute("file.export.exportPreferences", json!({"quickExportFormat": "jpg", "metadata": "all"})).unwrap();
+ let r = s.execute("file.export.quickExport", json!({"path": format!("{dir}/quick.jpg")})).unwrap();
+ assert!(r["warnings"][0].as_str().is_some_and(|w| w.contains("EXIF")), "{r}");
+ s.execute("prefs.reset", json!({"path": "export"})).unwrap();
+
+ for cut in [3, 9, 40, 100] {
+ let mut s = photo_session(camera_exif()[..cut].to_vec());
+ let path = format!("{dir}/cut{cut}.jpg");
+ s.execute("file.export.saveForWebLegacy", json!({"format": "jpeg", "metadata": "all", "path": path})).unwrap();
+ assert_eq!(decode(&path).dimensions(), (64, 48));
+ }
+}
diff --git a/crates/ui-egui/src/file_ui.rs b/crates/ui-egui/src/file_ui.rs
index d1b2f0e55..a84bfe777 100644
--- a/crates/ui-egui/src/file_ui.rs
+++ b/crates/ui-egui/src/file_ui.rs
@@ -1674,7 +1674,7 @@ mod web_playback_tests {
let doc = web_frame_document(&app.session.active().unwrap().doc, Some(frame)).unwrap();
let (proxy, _, _) = web_cmds::web_document(&doc, &json!({"width":16,"height":12}), &settings).unwrap();
let pixels = photocraft_compose::flatten(&proxy);
- let optimized = web_cmds::optimize(&pixels.px, 16, photocraft_geom::Rect::new(0, 0, 16, 12), &settings, None, None, 72.0, true).unwrap();
+ let optimized = web_cmds::optimize(&pixels.px, 16, photocraft_geom::Rect::new(0, 0, 16, 12), &settings, None, None, None, 72.0, true).unwrap();
assert_eq!(&optimized.preview[..4], expected, "depth={depth} frame={frame}");
}
}
diff --git a/crates/ui-egui/src/file_ui/web_preview.rs b/crates/ui-egui/src/file_ui/web_preview.rs
index a9ee7a933..b60358457 100644
--- a/crates/ui-egui/src/file_ui/web_preview.rs
+++ b/crates/ui-egui/src/file_ui/web_preview.rs
@@ -60,8 +60,8 @@ pub fn prepare_table(app: &PhotocraftApp, f: &mut Map<String, Value>) -> Result<
let (doc, _, _) = web_cmds::web_document(&st.doc, &proxy, &settings).map_err(|e| e.to_string())?;
f.insert("__paletteApproximate".into(), json!(scale < 1.0));
let buf = photocraft_compose::flatten(&doc);
- let mut optimized =
- web_cmds::optimize(&buf.px, doc.size.width as usize, doc.bounds(), &settings, None, None, doc.resolution_dpi, false).map_err(|e| e.to_string())?;
+ let mut optimized = web_cmds::optimize(&buf.px, doc.size.width as usize, doc.bounds(), &settings, None, None, None, doc.resolution_dpi, false)
+ .map_err(|e| e.to_string())?;
// Tiny transparent features may disappear in the proxy; keep room for their index.
if settings.transparency {
optimized.color_table.truncate(255);
@@ -137,7 +137,7 @@ pub fn optimized(ui: &mut egui::Ui, key: egui::Id, signature: &str, p: &Value, p
} else {
let settings = WebSettings::from_params(&base, "preview").map_err(|e| e.to_string())?;
let encoded = Arc::new(
- web_cmds::optimize(px, w as usize, photocraft_geom::Rect::new(0, 0, w as i32, h as i32), &settings, None, None, 72.0, true)
+ web_cmds::optimize(px, w as usize, photocraft_geom::Rect::new(0, 0, w as i32, h as i32), &settings, None, None, None, 72.0, true)
.map_err(|e| e.to_string())?,
);
ui.data_mut(|d| d.insert_temp(key, (signature, encoded.clone())));