From 91c9af9fd5ac0854cccef8cac17e17ff2fe8bb29 Mon Sep 17 00:00:00 2001 From: griffi-gh Date: Sun, 24 Mar 2024 22:55:05 +0100 Subject: [PATCH] add image loading --- hui/Cargo.toml | 9 +++++++-- hui/src/instance.rs | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/hui/Cargo.toml b/hui/Cargo.toml index 990e21c..a07657a 100644 --- a/hui/Cargo.toml +++ b/hui/Cargo.toml @@ -26,10 +26,15 @@ document-features = "0.2" derive_setters = "0.1" derive_more = "0.99" tinyset = "0.4" - +image = { version = "0.25", default-features = false, optional = true } [features] -default = ["el_all", "builtin_font", "pixel_perfect_text"] +default = ["el_all", "image", "builtin_font", "pixel_perfect_text"] + +#! Image loading support: + +## Enable image loading support using the `image` crate +image = ["dep:image"] #! #### Built-in font: diff --git a/hui/src/instance.rs b/hui/src/instance.rs index 96bf38d..fef361c 100644 --- a/hui/src/instance.rs +++ b/hui/src/instance.rs @@ -83,6 +83,44 @@ impl UiInstance { self.atlas.add(width, data, format) } + //TODO better error handling + + /// Add an image from a file to the texture atlas\ + /// (experimental, may be removed in the future) + /// + /// Requires the `image` feature + /// + /// # Panics: + /// - If the file exists but contains invalid image data\ + /// (this will change to a soft error in the future) + #[cfg(feature = "image")] + pub fn add_image_file_path(&mut self, path: impl AsRef) -> Result { + use std::io::Read; + + // Open the file (and wrap it in a bufreader) + let mut file = std::io::BufReader::new(std::fs::File::open(path)?); + + //Guess the image format from the magic bytes + //Read like 64 bytes, which should be enough for magic byte detection + //well this would fail if the image is somehow smaller than 64 bytes, but who the fvck cares... + let mut magic = [0; 64]; + file.read_exact(&mut magic)?; + let format = image::guess_format(&magic).expect("Invalid image data (FORMAT)"); + + //Parse the image and read the raw uncompressed rgba data + let image = image::load(file, format).expect("Invalid image data"); + let image_rgba = image.as_rgba8().unwrap(); + + //Add the image to the atlas + let handle = self.add_image( + TextureFormat::Rgba, + image_rgba, + image.width() as usize + ); + + Ok(handle) + } + /// Push a font to the font stack\ /// The font will be used for all text rendering until it is popped ///