Skip to main content

usvg/parser/
image.rs

1// Copyright 2018 the Resvg Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4use std::sync::{Arc, OnceLock};
5
6use svgtypes::{AspectRatio, Length};
7
8use super::svgtree::{AId, SvgNode};
9use super::{OptionLog, Options, converter};
10use crate::tree::GroupBoundingBoxes;
11use crate::{
12    ClipPath, Group, Image, ImageKind, ImageRendering, Node, NonZeroRect, Path, Size, Transform,
13    Tree, Visibility,
14};
15
16/// A shorthand for [ImageHrefResolver]'s data function.
17pub type ImageHrefDataResolverFn<'a> =
18    Box<dyn Fn(&str, Arc<Vec<u8>>, &Options) -> Option<ImageKind> + Send + Sync + 'a>;
19
20/// A shorthand for [ImageHrefResolver]'s string function.
21pub type ImageHrefStringResolverFn<'a> =
22    Box<dyn Fn(&str, &Options) -> Option<ImageKind> + Send + Sync + 'a>;
23
24/// An `xlink:href` resolver for `<image>` elements.
25///
26/// This type can be useful if you want to have an alternative `xlink:href` handling
27/// to the default one. For example, you can forbid access to local files (which is allowed by default)
28/// or add support for resolving actual URLs (usvg doesn't do any network requests).
29pub struct ImageHrefResolver<'a> {
30    /// Resolver function that will be used when `xlink:href` contains a
31    /// [Data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs).
32    ///
33    /// A function would be called with mime, decoded base64 data and parsing options.
34    pub resolve_data: ImageHrefDataResolverFn<'a>,
35
36    /// Resolver function that will be used to handle an arbitrary string in `xlink:href`.
37    pub resolve_string: ImageHrefStringResolverFn<'a>,
38}
39
40impl Default for ImageHrefResolver<'_> {
41    fn default() -> Self {
42        ImageHrefResolver {
43            resolve_data: ImageHrefResolver::default_data_resolver(),
44            resolve_string: ImageHrefResolver::default_string_resolver(),
45        }
46    }
47}
48
49impl ImageHrefResolver<'_> {
50    /// Creates a default
51    /// [Data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs)
52    /// resolver closure.
53    ///
54    /// base64 encoded data is already decoded.
55    ///
56    /// The default implementation would try to load JPEG, PNG, GIF, WebP, SVG and SVGZ types.
57    /// Note that it will simply match the `mime` or data's magic.
58    /// The actual images would not be decoded. It's up to the renderer.
59    pub fn default_data_resolver() -> ImageHrefDataResolverFn<'static> {
60        Box::new(
61            move |mime: &str, data: Arc<Vec<u8>>, opts: &Options| match mime {
62                "image/jpg" | "image/jpeg" => Some(ImageKind::JPEG(data)),
63                "image/png" => Some(ImageKind::PNG(data)),
64                "image/gif" => Some(ImageKind::GIF(data)),
65                "image/webp" => Some(ImageKind::WEBP(data)),
66                "image/svg+xml" => load_sub_svg(&data, opts),
67                "text/plain" => match get_image_data_format(&data) {
68                    Some(ImageFormat::JPEG) => Some(ImageKind::JPEG(data)),
69                    Some(ImageFormat::PNG) => Some(ImageKind::PNG(data)),
70                    Some(ImageFormat::GIF) => Some(ImageKind::GIF(data)),
71                    Some(ImageFormat::WEBP) => Some(ImageKind::WEBP(data)),
72                    _ => load_sub_svg(&data, opts),
73                },
74                _ => None,
75            },
76        )
77    }
78
79    /// Creates a default string resolver.
80    ///
81    /// The default implementation treats an input string as a file path and tries to open.
82    /// If a string is an URL or something else it would be ignored.
83    ///
84    /// Paths have to be absolute or relative to the input SVG file or relative to
85    /// [Options::resources_dir](crate::Options::resources_dir).
86    pub fn default_string_resolver() -> ImageHrefStringResolverFn<'static> {
87        Box::new(move |href: &str, opts: &Options| {
88            let path = opts.get_abs_path(std::path::Path::new(href));
89
90            if path.exists() {
91                let data = match std::fs::read(&path) {
92                    Ok(data) => data,
93                    Err(_) => {
94                        log::warn!("Failed to load '{}'. Skipped.", href);
95                        return None;
96                    }
97                };
98
99                match get_image_file_format(&path, &data) {
100                    Some(ImageFormat::JPEG) => Some(ImageKind::JPEG(Arc::new(data))),
101                    Some(ImageFormat::PNG) => Some(ImageKind::PNG(Arc::new(data))),
102                    Some(ImageFormat::GIF) => Some(ImageKind::GIF(Arc::new(data))),
103                    Some(ImageFormat::WEBP) => Some(ImageKind::WEBP(Arc::new(data))),
104                    Some(ImageFormat::SVG) => load_sub_svg(&data, opts),
105                    _ => {
106                        log::warn!("'{}' is not a PNG, JPEG, GIF, WebP or SVG(Z) image.", href);
107                        None
108                    }
109                }
110            } else {
111                log::warn!("'{}' is not a path to an image.", href);
112                None
113            }
114        })
115    }
116}
117
118impl std::fmt::Debug for ImageHrefResolver<'_> {
119    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
120        f.write_str("ImageHrefResolver { .. }")
121    }
122}
123
124#[derive(Clone, Copy, PartialEq, Debug)]
125enum ImageFormat {
126    PNG,
127    JPEG,
128    GIF,
129    WEBP,
130    SVG,
131}
132
133pub(crate) fn convert(
134    node: SvgNode,
135    state: &converter::State,
136    cache: &mut converter::Cache,
137    parent: &mut Group,
138) -> Option<()> {
139    let href = node
140        .try_attribute(AId::Href)
141        .log_none(|| log::warn!("Image lacks the 'xlink:href' attribute. Skipped."))?;
142
143    let kind = get_href_data(href, state)?;
144
145    let visibility: Visibility = node.find_attribute(AId::Visibility).unwrap_or_default();
146    let visible = visibility == Visibility::Visible;
147
148    let rendering_mode = node
149        .find_attribute(AId::ImageRendering)
150        .unwrap_or(state.opt.image_rendering);
151
152    // Nodes generated by markers must not have an ID. Otherwise we would have duplicates.
153    let id = if !state.inside_marker {
154        node.element_id().to_string()
155    } else {
156        String::new()
157    };
158
159    let actual_size = kind.actual_size()?;
160
161    let x = node.convert_user_length(AId::X, state, Length::zero());
162    let y = node.convert_user_length(AId::Y, state, Length::zero());
163    let mut width = node.convert_user_length(
164        AId::Width,
165        state,
166        Length::new_number(actual_size.width() as f64),
167    );
168    let mut height = node.convert_user_length(
169        AId::Height,
170        state,
171        Length::new_number(actual_size.height() as f64),
172    );
173
174    match (
175        node.attribute::<Length>(AId::Width),
176        node.attribute::<Length>(AId::Height),
177    ) {
178        (Some(_), None) => {
179            // Only width was defined, so we need to scale height accordingly.
180            height = actual_size.height() * (width / actual_size.width());
181        }
182        (None, Some(_)) => {
183            // Only height was defined, so we need to scale width accordingly.
184            width = actual_size.width() * (height / actual_size.height());
185        }
186        _ => {}
187    };
188
189    let aspect: AspectRatio = node.attribute(AId::PreserveAspectRatio).unwrap_or_default();
190
191    let rect = NonZeroRect::from_xywh(x, y, width, height);
192    let rect = rect.log_none(|| log::warn!("Image has an invalid size. Skipped."))?;
193
194    convert_inner(
195        kind,
196        id,
197        visible,
198        rendering_mode,
199        aspect,
200        actual_size,
201        rect,
202        cache,
203        parent,
204    )
205}
206
207pub(crate) fn convert_inner(
208    kind: ImageKind,
209    id: String,
210    visible: bool,
211    rendering_mode: ImageRendering,
212    aspect: AspectRatio,
213    actual_size: Size,
214    rect: NonZeroRect,
215    cache: &mut converter::Cache,
216    parent: &mut Group,
217) -> Option<()> {
218    let aligned_size = fit_view_box(actual_size, rect, aspect);
219    let (aligned_x, aligned_y) = crate::aligned_pos(
220        aspect.align,
221        rect.x(),
222        rect.y(),
223        rect.width() - aligned_size.width(),
224        rect.height() - aligned_size.height(),
225    );
226    let view_box = aligned_size.to_non_zero_rect(aligned_x, aligned_y);
227
228    let image_ts = Transform::from_row(
229        view_box.width() / actual_size.width(),
230        0.0,
231        0.0,
232        view_box.height() / actual_size.height(),
233        view_box.x(),
234        view_box.y(),
235    );
236
237    let abs_transform = parent.abs_transform.pre_concat(image_ts);
238    let abs_bounding_box = view_box.transform(parent.abs_transform)?;
239
240    let mut g = Group::empty();
241    g.id = id;
242    g.children.push(Node::Image(Box::new(Image {
243        id: String::new(),
244        visible,
245        size: actual_size,
246        rendering_mode,
247        kind,
248        abs_transform,
249        abs_bounding_box,
250    })));
251    g.transform = image_ts;
252    g.abs_transform = abs_transform;
253
254    if aspect.slice {
255        // Image slice acts like a rectangular clip.
256        let mut path = Path::new_simple(Arc::new(tiny_skia_path::PathBuilder::from_rect(
257            rect.to_rect(),
258        )));
259        path.fill = Some(crate::Fill::default());
260
261        let mut clip = ClipPath::empty(cache.gen_clip_path_id());
262        clip.root.children.push(Node::Path(Box::new(path)));
263
264        // Clip path should not be affected by the image viewbox transform.
265        // The final structure should look like:
266        // <g clip-path="url(#clipPath1)">
267        //     <g transform="matrix(1 0 0 1 10 20)">
268        //         <image/>
269        //     </g>
270        // </g>
271
272        let mut g2 = Group::empty();
273        std::mem::swap(&mut g.id, &mut g2.id);
274        g2.abs_transform = parent.abs_transform;
275        g2.clip_path = Some(Arc::new(clip));
276        g2.children.push(Node::Group(Box::new(g)));
277
278        // With `slice`, the image is scaled to *cover* the viewport and the
279        // overflow is cut away by the rectangular clip above. The bounding box
280        // of the element is therefore its `rect` (the viewport), not the
281        // larger scaled-to-cover image that the children's bounding boxes
282        // would give. Without this correction an `objectBoundingBox`
283        // clip/mask/filter applied to the `<image>` would be resolved against
284        // the oversized image. See https://github.com/linebender/resvg/issues/1034
285        let bbox = rect.to_rect();
286        let mut bounding_boxes = GroupBoundingBoxes {
287            bounding_box: OnceLock::from(Some(bbox)),
288            stroke_bounding_box: OnceLock::from(Some(bbox)),
289            ..GroupBoundingBoxes::default()
290        };
291        if let Some(abs) = bbox.transform(g2.abs_transform) {
292            bounding_boxes.abs_bounding_box = OnceLock::from(Some(abs));
293            bounding_boxes.abs_stroke_bounding_box = OnceLock::from(Some(abs));
294        }
295        g2.bounding_boxes = OnceLock::from(Box::new(bounding_boxes));
296
297        parent.children.push(Node::Group(Box::new(g2)));
298    } else {
299        parent.children.push(Node::Group(Box::new(g)));
300    }
301
302    Some(())
303}
304
305pub(crate) fn get_href_data(href: &str, state: &converter::State) -> Option<ImageKind> {
306    if let Ok(url) = data_url::DataUrl::process(href) {
307        let (data, _) = url.decode_to_vec().ok()?;
308
309        let mime = format!(
310            "{}/{}",
311            url.mime_type().type_.as_str(),
312            url.mime_type().subtype.as_str()
313        );
314
315        (state.opt.image_href_resolver.resolve_data)(&mime, Arc::new(data), state.opt)
316    } else {
317        (state.opt.image_href_resolver.resolve_string)(href, state.opt)
318    }
319}
320
321/// Checks that file has a PNG, a GIF, a JPEG or a WebP magic bytes.
322/// Or an SVG(Z) extension.
323fn get_image_file_format(path: &std::path::Path, data: &[u8]) -> Option<ImageFormat> {
324    let ext = path.extension().and_then(|e| e.to_str())?.to_lowercase();
325    if ext == "svg" || ext == "svgz" {
326        return Some(ImageFormat::SVG);
327    }
328
329    get_image_data_format(data)
330}
331
332/// Checks that file has a PNG, a GIF, a JPEG or a WebP magic bytes.
333fn get_image_data_format(data: &[u8]) -> Option<ImageFormat> {
334    match imagesize::image_type(data).ok()? {
335        imagesize::ImageType::Gif => Some(ImageFormat::GIF),
336        imagesize::ImageType::Jpeg => Some(ImageFormat::JPEG),
337        imagesize::ImageType::Png => Some(ImageFormat::PNG),
338        imagesize::ImageType::Webp => Some(ImageFormat::WEBP),
339        _ => None,
340    }
341}
342
343/// Tries to load the `ImageData` content as an SVG image or emits a warning and returns `None`.
344pub(crate) fn load_sub_svg(data: &[u8], opt: &Options) -> Option<ImageKind> {
345    match Tree::from_data_nested(data, opt) {
346        Ok(tree) => Some(ImageKind::SVG(tree)),
347        Err(_) => {
348            log::warn!("Failed to load nested SVG image.");
349            None
350        }
351    }
352}
353
354/// Fits size into a viewbox.
355fn fit_view_box(size: Size, rect: NonZeroRect, aspect: AspectRatio) -> Size {
356    let s = rect.size();
357
358    if aspect.align == svgtypes::Align::None {
359        s
360    } else if aspect.slice {
361        size.expand_to(s)
362    } else {
363        size.scale_to(s)
364    }
365}