Skip to content

Commit

Permalink
Add support for decoding WebP images
Browse files Browse the repository at this point in the history
  • Loading branch information
notjosh committed Jul 22, 2024
1 parent 1a6922d commit 6e26621
Show file tree
Hide file tree
Showing 12 changed files with 137 additions and 11 deletions.
23 changes: 23 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion crates/resvg/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ required-features = ["text", "system-fonts", "memmap-fonts"]

[dependencies]
gif = { version = "0.13", optional = true }
image-webp = { version = "0.1.3", optional = true }
log = "0.4"
pico-args = { version = "0.5", features = ["eq-separator"] }
rgb = "0.8"
Expand All @@ -40,4 +41,4 @@ memmap-fonts = ["usvg/memmap-fonts"]
# Enables decoding and rendering of raster images.
# When disabled, `image` elements with SVG data will still be rendered.
# Adds around 200KiB to your binary.
raster-images = ["gif", "dep:zune-jpeg"]
raster-images = ["gif", "image-webp", "dep:zune-jpeg"]
35 changes: 35 additions & 0 deletions crates/resvg/src/image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,9 @@ mod raster_images {
usvg::ImageKind::GIF(ref data) => {
decode_gif(data).log_none(|| log::warn!("Failed to decode a GIF image."))
}
usvg::ImageKind::WEBP(ref data) => {
decode_webp(data).log_none(|| log::warn!("Failed to decode a WebP image."))
}
}
}

Expand Down Expand Up @@ -107,6 +110,38 @@ mod raster_images {
Some(pixmap)
}

fn decode_webp(data: &[u8]) -> Option<tiny_skia::Pixmap> {
let mut decoder = image_webp::WebPDecoder::new(std::io::Cursor::new(data)).ok()?;
let mut first_frame = vec![0; decoder.output_buffer_size()?];
decoder.read_image(&mut first_frame).ok()?;

let (w, h) = decoder.dimensions();
let mut pixmap = tiny_skia::Pixmap::new(w, h)?;

if decoder.has_alpha() {
rgba_to_pixmap(&first_frame, &mut pixmap);
} else {
rgb_to_pixmap(&first_frame, &mut pixmap);
}

Some(pixmap)
}

fn rgb_to_pixmap(data: &[u8], pixmap: &mut tiny_skia::Pixmap) {
use rgb::FromSlice;

let mut i = 0;
let dst = pixmap.data_mut();
for p in data.as_rgb() {
dst[i + 0] = p.r;
dst[i + 1] = p.g;
dst[i + 2] = p.b;
dst[i + 3] = 255;

i += tiny_skia::BYTES_PER_PIXEL;
}
}

fn rgba_to_pixmap(data: &[u8], pixmap: &mut tiny_skia::Pixmap) {
use rgb::FromSlice;

Expand Down
2 changes: 2 additions & 0 deletions crates/resvg/tests/integration/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1101,12 +1101,14 @@ use crate::render;
#[test] fn structure_image_embedded_svg_without_mime() { assert_eq!(render("tests/structure/image/embedded-svg-without-mime"), 0); }
#[test] fn structure_image_embedded_svg() { assert_eq!(render("tests/structure/image/embedded-svg"), 0); }
#[test] fn structure_image_embedded_svgz() { assert_eq!(render("tests/structure/image/embedded-svgz"), 0); }
#[test] fn structure_image_embedded_webp() { assert_eq!(render("tests/structure/image/embedded-webp"), 0); }
#[test] fn structure_image_external_gif() { assert_eq!(render("tests/structure/image/external-gif"), 0); }
#[test] fn structure_image_external_jpeg() { assert_eq!(render("tests/structure/image/external-jpeg"), 0); }
#[test] fn structure_image_external_png() { assert_eq!(render("tests/structure/image/external-png"), 0); }
#[test] fn structure_image_external_svg_with_transform() { assert_eq!(render("tests/structure/image/external-svg-with-transform"), 0); }
#[test] fn structure_image_external_svg() { assert_eq!(render("tests/structure/image/external-svg"), 0); }
#[test] fn structure_image_external_svgz() { assert_eq!(render("tests/structure/image/external-svgz"), 0); }
#[test] fn structure_image_external_webp() { assert_eq!(render("tests/structure/image/external-webp"), 0); }
#[test] fn structure_image_float_size() { assert_eq!(render("tests/structure/image/float-size"), 0); }
#[test] fn structure_image_image_with_float_size_scaling() { assert_eq!(render("tests/structure/image/image-with-float-size-scaling"), 0); }
#[test] fn structure_image_no_height_non_square() { assert_eq!(render("tests/structure/image/no-height-non-square"), 0); }
Expand Down
Binary file added crates/resvg/tests/resources/image.webp
Binary file not shown.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
47 changes: 47 additions & 0 deletions crates/resvg/tests/tests/structure/image/embedded-webp.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
8 changes: 8 additions & 0 deletions crates/resvg/tests/tests/structure/image/external-webp.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
13 changes: 9 additions & 4 deletions crates/usvg/src/parser/image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ impl ImageHrefResolver<'_> {
///
/// base64 encoded data is already decoded.
///
/// The default implementation would try to load JPEG, PNG, GIF, SVG and SVGZ types.
/// The default implementation would try to load JPEG, PNG, GIF, WebP, SVG and SVGZ types.
/// Note that it will simply match the `mime` or data's magic.
/// The actual images would not be decoded. It's up to the renderer.
pub fn default_data_resolver() -> ImageHrefDataResolverFn<'static> {
Expand All @@ -62,11 +62,13 @@ impl ImageHrefResolver<'_> {
"image/jpg" | "image/jpeg" => Some(ImageKind::JPEG(data)),
"image/png" => Some(ImageKind::PNG(data)),
"image/gif" => Some(ImageKind::GIF(data)),
"image/webp" => Some(ImageKind::WEBP(data)),
"image/svg+xml" => load_sub_svg(&data, opts),
"text/plain" => match get_image_data_format(&data) {
Some(ImageFormat::JPEG) => Some(ImageKind::JPEG(data)),
Some(ImageFormat::PNG) => Some(ImageKind::PNG(data)),
Some(ImageFormat::GIF) => Some(ImageKind::GIF(data)),
Some(ImageFormat::WEBP) => Some(ImageKind::WEBP(data)),
_ => load_sub_svg(&data, opts),
},
_ => None,
Expand Down Expand Up @@ -98,9 +100,10 @@ impl ImageHrefResolver<'_> {
Some(ImageFormat::JPEG) => Some(ImageKind::JPEG(Arc::new(data))),
Some(ImageFormat::PNG) => Some(ImageKind::PNG(Arc::new(data))),
Some(ImageFormat::GIF) => Some(ImageKind::GIF(Arc::new(data))),
Some(ImageFormat::WEBP) => Some(ImageKind::WEBP(Arc::new(data))),
Some(ImageFormat::SVG) => load_sub_svg(&data, opts),
_ => {
log::warn!("'{}' is not a PNG, JPEG, GIF or SVG(Z) image.", href);
log::warn!("'{}' is not a PNG, JPEG, GIF, WebP or SVG(Z) image.", href);
None
}
}
Expand All @@ -123,6 +126,7 @@ enum ImageFormat {
PNG,
JPEG,
GIF,
WEBP,
SVG,
}

Expand Down Expand Up @@ -298,7 +302,7 @@ pub(crate) fn get_href_data(href: &str, state: &converter::State) -> Option<Imag
}
}

/// Checks that file has a PNG, a GIF or a JPEG magic bytes.
/// Checks that file has a PNG, a GIF, a JPEG or a WebP magic bytes.
/// Or an SVG(Z) extension.
fn get_image_file_format(path: &std::path::Path, data: &[u8]) -> Option<ImageFormat> {
let ext = path.extension().and_then(|e| e.to_str())?.to_lowercase();
Expand All @@ -309,12 +313,13 @@ fn get_image_file_format(path: &std::path::Path, data: &[u8]) -> Option<ImageFor
get_image_data_format(data)
}

/// Checks that file has a PNG, a GIF or a JPEG magic bytes.
/// Checks that file has a PNG, a GIF, a JPEG or a WebP magic bytes.
fn get_image_data_format(data: &[u8]) -> Option<ImageFormat> {
match imagesize::image_type(data).ok()? {
imagesize::ImageType::Gif => Some(ImageFormat::GIF),
imagesize::ImageType::Jpeg => Some(ImageFormat::JPEG),
imagesize::ImageType::Png => Some(ImageFormat::PNG),
imagesize::ImageType::Webp => Some(ImageFormat::WEBP),
_ => None,
}
}
Expand Down
16 changes: 10 additions & 6 deletions crates/usvg/src/tree/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1424,19 +1424,22 @@ pub enum ImageKind {
PNG(Arc<Vec<u8>>),
/// A reference to raw GIF data. Should be decoded by the caller.
GIF(Arc<Vec<u8>>),
/// A reference to raw WebP data. Should be decoded by the caller.
WEBP(Arc<Vec<u8>>),
/// A preprocessed SVG tree. Can be rendered as is.
SVG(Tree),
}

impl ImageKind {
pub(crate) fn actual_size(&self) -> Option<Size> {
match self {
ImageKind::JPEG(ref data) | ImageKind::PNG(ref data) | ImageKind::GIF(ref data) => {
imagesize::blob_size(data)
.ok()
.and_then(|size| Size::from_wh(size.width as f32, size.height as f32))
.log_none(|| log::warn!("Image has an invalid size. Skipped."))
}
ImageKind::JPEG(ref data)
| ImageKind::PNG(ref data)
| ImageKind::GIF(ref data)
| ImageKind::WEBP(ref data) => imagesize::blob_size(data)
.ok()
.and_then(|size| Size::from_wh(size.width as f32, size.height as f32))
.log_none(|| log::warn!("Image has an invalid size. Skipped.")),
ImageKind::SVG(ref svg) => Some(svg.size),
}
}
Expand All @@ -1448,6 +1451,7 @@ impl std::fmt::Debug for ImageKind {
ImageKind::JPEG(_) => f.write_str("ImageKind::JPEG(..)"),
ImageKind::PNG(_) => f.write_str("ImageKind::PNG(..)"),
ImageKind::GIF(_) => f.write_str("ImageKind::GIF(..)"),
ImageKind::WEBP(_) => f.write_str("ImageKind::WEBP(..)"),
ImageKind::SVG(_) => f.write_str("ImageKind::SVG(..)"),
}
}
Expand Down
1 change: 1 addition & 0 deletions crates/usvg/src/writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1073,6 +1073,7 @@ impl XmlWriterExt for XmlWriter {
ImageKind::JPEG(ref data) => ("jpeg", data.as_slice()),
ImageKind::PNG(ref data) => ("png", data.as_slice()),
ImageKind::GIF(ref data) => ("gif", data.as_slice()),
ImageKind::WEBP(ref data) => ("webp", data.as_slice()),
ImageKind::SVG(ref tree) => {
svg_string = tree.to_string(&WriteOptions::default());
("svg+xml", svg_string.as_bytes())
Expand Down

0 comments on commit 6e26621

Please sign in to comment.