summaryrefslogtreecommitdiff
path: root/src/image.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/image.rs')
-rw-r--r--src/image.rs98
1 files changed, 91 insertions, 7 deletions
diff --git a/src/image.rs b/src/image.rs
index 512b24b1..a7b62503 100644
--- a/src/image.rs
+++ b/src/image.rs
@@ -1,6 +1,7 @@
//! Image handling.
use std::collections::{hash_map::Entry, HashMap};
+use std::ffi::OsStr;
use std::fmt::{self, Debug, Formatter};
use std::io;
use std::path::Path;
@@ -65,7 +66,8 @@ impl ImageStore {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => {
let buffer = self.loader.load(path)?;
- let image = Image::parse(&buffer)?;
+ let ext = path.extension().and_then(OsStr::to_str).unwrap_or_default();
+ let image = Image::parse(&buffer, &ext)?;
let id = ImageId(self.images.len() as u32);
if let Some(callback) = &self.on_load {
callback(id, &image);
@@ -88,23 +90,71 @@ impl ImageStore {
}
/// A loaded image.
-pub struct Image {
+#[derive(Debug)]
+pub enum Image {
+ /// A pixel raster format, like PNG or JPEG.
+ Raster(RasterImage),
+ /// An SVG vector graphic.
+ Svg(Svg),
+}
+
+impl Image {
+ /// Parse an image from raw data. The file extension is used as a hint for
+ /// which error message describes the problem best.
+ pub fn parse(data: &[u8], ext: &str) -> io::Result<Self> {
+ match Svg::parse(data) {
+ Ok(svg) => return Ok(Self::Svg(svg)),
+ Err(err) if matches!(ext, "svg" | "svgz") => return Err(err),
+ Err(_) => {}
+ }
+
+ match RasterImage::parse(data) {
+ Ok(raster) => return Ok(Self::Raster(raster)),
+ Err(err) if matches!(ext, "png" | "jpg" | "jpeg") => return Err(err),
+ Err(_) => {}
+ }
+
+ Err(io::Error::new(
+ io::ErrorKind::InvalidData,
+ "unknown image format",
+ ))
+ }
+
+ /// The width of the image in pixels.
+ pub fn width(&self) -> u32 {
+ match self {
+ Self::Raster(image) => image.width(),
+ Self::Svg(image) => image.width(),
+ }
+ }
+
+ /// The height of the image in pixels.
+ pub fn height(&self) -> u32 {
+ match self {
+ Self::Raster(image) => image.height(),
+ Self::Svg(image) => image.height(),
+ }
+ }
+}
+
+/// A raster image, supported through the image crate.
+pub struct RasterImage {
/// The original format the image was encoded in.
pub format: ImageFormat,
/// The decoded image.
pub buf: DynamicImage,
}
-impl Image {
+impl RasterImage {
/// Parse an image from raw data in a supported format (PNG or JPEG).
///
/// The image format is determined automatically.
pub fn parse(data: &[u8]) -> io::Result<Self> {
let cursor = io::Cursor::new(data);
let reader = ImageReader::new(cursor).with_guessed_format()?;
- let format = reader.format().ok_or_else(|| {
- io::Error::new(io::ErrorKind::InvalidData, "unknown image format")
- })?;
+ let format = reader
+ .format()
+ .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidData))?;
let buf = reader
.decode()
@@ -124,7 +174,7 @@ impl Image {
}
}
-impl Debug for Image {
+impl Debug for RasterImage {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.debug_struct("Image")
.field("format", &self.format)
@@ -134,3 +184,37 @@ impl Debug for Image {
.finish()
}
}
+
+/// An SVG image, supported through the usvg crate.
+pub struct Svg(pub usvg::Tree);
+
+impl Svg {
+ /// Parse an SVG file from a data buffer. This also handles `.svgz`
+ /// compressed files.
+ pub fn parse(data: &[u8]) -> io::Result<Self> {
+ let usvg_opts = usvg::Options::default();
+ usvg::Tree::from_data(data, &usvg_opts.to_ref())
+ .map(Self)
+ .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))
+ }
+
+ /// The width of the image in rounded-up nominal SVG pixels.
+ pub fn width(&self) -> u32 {
+ self.0.svg_node().size.width().ceil() as u32
+ }
+
+ /// The height of the image in rounded-up nominal SVG pixels.
+ pub fn height(&self) -> u32 {
+ self.0.svg_node().size.height().ceil() as u32
+ }
+}
+
+impl Debug for Svg {
+ fn fmt(&self, f: &mut Formatter) -> fmt::Result {
+ f.debug_struct("Svg")
+ .field("width", &self.0.svg_node().size.width())
+ .field("height", &self.0.svg_node().size.height())
+ .field("viewBox", &self.0.svg_node().view_box)
+ .finish()
+ }
+}