diff --git a/Cargo.toml b/Cargo.toml index f91e4a840a..d08a9ce70b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -96,6 +96,11 @@ iced_core = { version = "0.4", path = "core" } iced_futures = { version = "0.3", path = "futures" } thiserror = "1.0" +[dependencies.image_rs] +version = "0.23" +package = "image" +optional = true + [target.'cfg(not(target_arch = "wasm32"))'.dependencies] iced_winit = { version = "0.3", path = "winit" } iced_glutin = { version = "0.2", path = "glutin", optional = true } diff --git a/src/window/icon.rs b/src/window/icon.rs index 287538b13f..7b4178b6ba 100644 --- a/src/window/icon.rs +++ b/src/window/icon.rs @@ -1,6 +1,7 @@ //! Attach an icon to the window of your application. use std::fmt; use std::io; +use std::path::Path; /// The icon of a window. #[cfg(not(target_arch = "wasm32"))] @@ -35,6 +36,40 @@ impl Icon { ) -> Result { Ok(Icon) } + + /// Creates an icon from an image file. + /// + /// This will return an error in case the file is missing at run-time. You may prefer [`Self::from_file_data`] instead. + #[cfg(feature = "image_rs")] + pub fn from_file>(icon_path: P) -> Result { + let icon = image_rs::io::Reader::open(icon_path)? + .decode()? + .to_rgba8(); + + Self::from_rgba(icon.to_vec(), icon.width(), icon.height()) + } + + /// Creates an icon from the content of an image file. + /// + /// This content can be included in your application at compile-time, e.g. using the `include_bytes!` macro. \ + /// You can pass an explicit file format. Otherwise, the file format will be guessed at runtime. + #[cfg(feature = "image_rs")] + pub fn from_file_data(data: &[u8], explicit_format: Option) -> Result { + let mut icon = image_rs::io::Reader::new(std::io::Cursor::new(data)); + let icon_with_format = match explicit_format { + Some(format) => { + icon.set_format(format); + icon + }, + None => icon.with_guessed_format()?, + }; + + let pixels = icon_with_format + .decode()? + .to_rgba8(); + + Self::from_rgba(pixels.to_vec(), pixels.width(), pixels.height()) + } } /// An error produced when using `Icon::from_rgba` with invalid arguments. @@ -60,6 +95,15 @@ pub enum Error { /// The underlying OS failed to create the icon. OsError(io::Error), + + /// The `image` crate reported an error + ImageError(image_rs::error::ImageError), +} + +impl From for Error { + fn from(os_error: std::io::Error) -> Self { + Error::OsError(os_error) + } } #[cfg(not(target_arch = "wasm32"))] @@ -93,6 +137,14 @@ impl From for iced_winit::winit::window::Icon { } } +#[cfg(feature = "image_rs")] +impl From for Error { + fn from(image_error: image_rs::error::ImageError) -> Self { + Self::ImageError(image_error) + } +} + + impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { @@ -123,6 +175,11 @@ impl fmt::Display for Error { icon: {:?}", e ), + Error::ImageError(e) => write!( + f, + "Unable to create icon from a file: {:?}", + e + ), } } }