Add explicit error handling to image loading

This commit is contained in:
Héctor Ramón Jiménez 2025-10-28 21:19:25 +01:00
parent 7c11ccb046
commit 867fe819c0
No known key found for this signature in database
GPG key ID: 7CC46565708259A7
17 changed files with 357 additions and 118 deletions

View file

@ -6,6 +6,8 @@ use crate::core::Rectangle;
use crate::core::image;
use crate::core::svg;
use std::sync::Arc;
/// A raster or vector image.
#[allow(missing_docs)]
#[derive(Debug, Clone, PartialEq)]
@ -37,14 +39,14 @@ impl Image {
}
}
/// An image buffer.
pub type Buffer = ::image::ImageBuffer<::image::Rgba<u8>, image::Bytes>;
#[cfg(feature = "image")]
/// Tries to load an image by its [`Handle`].
///
/// [`Handle`]: image::Handle
pub fn load(
handle: &image::Handle,
) -> ::image::ImageResult<::image::ImageBuffer<::image::Rgba<u8>, image::Bytes>>
{
pub fn load(handle: &image::Handle) -> Result<Buffer, image::Error> {
use bitflags::bitflags;
bitflags! {
@ -96,7 +98,7 @@ pub fn load(
let (width, height, pixels) = match handle {
image::Handle::Path(_, path) => {
let image = ::image::open(path)?;
let image = ::image::open(path).map_err(to_error)?;
let operation = std::fs::File::open(path)
.ok()
@ -113,7 +115,8 @@ pub fn load(
)
}
image::Handle::Bytes(_, bytes) => {
let image = ::image::load_from_memory(bytes)?;
let image = ::image::load_from_memory(bytes).map_err(to_error)?;
let operation =
Operation::from_exif(&mut std::io::Cursor::new(bytes))
.ok()
@ -138,10 +141,19 @@ pub fn load(
if let Some(image) = ::image::ImageBuffer::from_raw(width, height, pixels) {
Ok(image)
} else {
Err(::image::error::ImageError::Limits(
Err(to_error(::image::error::ImageError::Limits(
::image::error::LimitError::from_kind(
::image::error::LimitErrorKind::DimensionError,
),
))
)))
}
}
fn to_error(error: ::image::ImageError) -> image::Error {
match error {
::image::ImageError::IoError(error) => {
image::Error::Inaccessible(Arc::new(error))
}
error => image::Error::Invalid(Arc::new(error)),
}
}