DOCX #2532: preserve imported picture soft edges

This commit is contained in:
Rees
2026-11-20 05:59:01 +01:00
parent 380a2f79f6
commit 8eae257cf3
4 changed files with 65 additions and 10 deletions
+10 -2
View File
@@ -291,7 +291,8 @@ impl Reader<'_> {
/// A picture: the first `a:blip` in `pic` and its crop.
fn read_pic(&mut self, pic: &El, rels: &Rels, w: f32, h: f32, alt: String, mut float: Float) -> Option<InlineObject> {
let blip = pic.find("a:blip")?;
float.set_spin(xfrm_spin(pic.find("pic:spPr")));
let props = pic.find("pic:spPr");
float.set_spin(xfrm_spin(props));
let Some(embed) = blip.attr("r:embed") else {
// A linked picture holds no copy: nothing to draw, and nothing is fetched.
if let Some(link) = blip.attr("r:link") {
@@ -311,7 +312,14 @@ impl Reader<'_> {
}
}
}
Some(InlineObject::Image { media, w, h, alt, float, crop, fx: crate::units::blip_fx(blip), ole: None })
let radius = props
.and_then(|e| e.child("a:effectLst"))
.and_then(|e| e.child("a:softEdge"))
.and_then(|e| e.attr("rad"))
.and_then(|value| value.parse().ok())
.unwrap_or(0);
let fx = crate::units::blip_fx(blip).with_soft_edge_emu(radius);
Some(InlineObject::Image { media, w, h, alt, float, crop, fx, ole: None })
}
/// A `wpg:wgp` group (`w` × `h`): its pictures, shapes and text boxes, nested groups
+6 -1
View File
@@ -39,7 +39,7 @@ impl Writer<'_> {
// Brightness, contrast and transparency (#1711, #1766) as `a:blip` effects (ECMA-376
// §20.1.8.13 CT_Blip: an unbounded choice of effects, in any order).
let fx = fx.clamped();
if fx.is_identity() {
if !fx.changes_pixels() && fx.transparency == 0 {
w.empty("a:blip", &[("r:embed", &rid)]);
} else {
w.open("a:blip", &[("r:embed", &rid)]);
@@ -64,6 +64,11 @@ impl Writer<'_> {
w.open("a:prstGeom", &[("prst", "rect")]);
w.empty("a:avLst", &[]);
w.close("a:prstGeom");
if let Some(radius) = fx.soft_edge_emu {
w.open("a:effectLst", &[]);
w.empty("a:softEdge", &[("rad", &n(i64::from(radius)))]);
w.close("a:effectLst");
}
w.close("pic:spPr");
w.close("pic:pic");
}
+26
View File
@@ -158,3 +158,29 @@ fn own_picture_fill_keeps_image() {
assert_eq!((float.wrap, float.x, float.y), (Wrap::InFrontOfText, 72.0, 100.0));
assert_eq!(doc.media[media].as_slice(), BLUE_PNG);
}
#[test]
fn nested_picture_soft_edges_survive_repeated_saves() {
use std::io::Read;
for (input_radius, expected_radius) in [(76_200, Some(76_200)), (0, None), (-1, None), (i64::MAX, Some(1_270_000))] {
let effect = format!(r#"<a:effectLst><a:softEdge rad="{input_radius}"/></a:effectLst></pic:spPr>"#);
let mut bytes = package(&INLINE_XML.replace("</pic:spPr>", &effect));
for _ in 0..2 {
let doc = craft_docx::read(&bytes).unwrap();
check_box(&doc);
bytes = craft_docx::write(&doc).unwrap();
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
let mut xml = String::new();
zip.by_name("word/document.xml").unwrap().read_to_string(&mut xml).unwrap();
// The text box's DrawingML and VML fallback can both carry the same picture.
let mut effects = xml.split("<a:softEdge ").skip(1).peekable();
assert_eq!(effects.peek().is_some(), expected_radius.is_some(), "{input_radius}");
if let Some(radius) = expected_radius {
let attr = format!(r#"rad="{radius}""#);
assert!(effects.all(|e| e.starts_with(&attr)), "{xml}");
}
}
check_box(&craft_docx::read(&bytes).unwrap());
}
}
+23 -7
View File
@@ -1,9 +1,9 @@
//! Picture colour corrections read from a file: brightness, contrast and transparency
//! Picture effects read from a file: brightness, contrast, transparency and soft edges
//! (DrawingML `a:lum` and `a:alphaModFix` inside `a:blip`, ECMA-376 §20.1.8.42 and §20.1.8.4;
//! VML `v:imagedata` `gain` and `blacklevel`, which Word's picture watermark "Washout" sets).
//!
//! Values are kept in OOXML units: thousandths of a percent, so 100 000 is 100 %. All zero is
//! the picture as it is.
//! Colour corrections use OOXML's thousandths of a percent, so 100 000 is 100 %. A picture's
//! DrawingML soft-edge radius uses EMUs, independent of its shared image pixels.
//!
//! The pixel formula was measured on Word (#1711, #1766): Word bakes the corrected pixels into
//! the picture it embeds in a PDF export, so a synthetic grey and colour ramp exported with
@@ -30,7 +30,9 @@ use serde::{Deserialize, Serialize};
/// The largest magnitude of a correction (100 %).
pub const FX_MAX: i32 = 100_000;
/// Brightness, contrast and transparency of a picture (see the module docs).
const MAX_SOFT_EDGE_EMU: i64 = crate::effects::MAX_SOFT_EDGE as i64 * 12_700;
/// Per-picture effects (see the module docs).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(default)]
pub struct PicFx {
@@ -40,17 +42,31 @@ pub struct PicFx {
pub contrast: i32,
/// 0 (opaque) ..= 100 000 (invisible).
pub transparency: i32,
/// Radius of a DrawingML soft edge in EMUs. An absent or zero radius leaves a sharp edge.
#[serde(skip_serializing_if = "Option::is_none")]
pub soft_edge_emu: Option<u32>,
}
impl PicFx {
/// Corrections clamped to their ranges.
pub fn new(bright: i32, contrast: i32, transparency: i32) -> PicFx {
PicFx { bright: bright.clamp(-FX_MAX, FX_MAX), contrast: contrast.clamp(-FX_MAX, FX_MAX), transparency: transparency.clamp(0, FX_MAX) }
PicFx {
bright: bright.clamp(-FX_MAX, FX_MAX),
contrast: contrast.clamp(-FX_MAX, FX_MAX),
transparency: transparency.clamp(0, FX_MAX),
soft_edge_emu: None,
}
}
/// The same corrections, each clamped to its range (for values that came from anywhere).
pub fn clamped(self) -> PicFx {
PicFx::new(self.bright, self.contrast, self.transparency)
PicFx::new(self.bright, self.contrast, self.transparency).with_soft_edge_emu(self.soft_edge_emu.map_or(0, i64::from))
}
/// Sets and bounds the picture's soft-edge radius without changing its other effects.
pub fn with_soft_edge_emu(mut self, radius: i64) -> Self {
self.soft_edge_emu = u32::try_from(radius.clamp(0, MAX_SOFT_EDGE_EMU)).ok().filter(|&value| value != 0);
self
}
/// No correction at all.
@@ -174,7 +190,7 @@ mod tests {
#[test]
fn hostile_values_clamp() {
for v in [i32::MIN, -100_001, 0, 100_001, i32::MAX] {
let fx = PicFx { bright: v, contrast: v, transparency: v };
let fx = PicFx { bright: v, contrast: v, transparency: v, ..Default::default() };
let _ = fx.table();
assert!((0.0..=1.0).contains(&fx.opacity()));
let mut px = [1u8, 2, 3, 4];