1
0
mirror of https://github.com/emilk/egui.git synced 2026-06-27 07:03:14 -04:00
Files
egui/crates/eframe/src/icon_data.rs
Emil Ernerfeldt 44d65f41ac Update image crate to 0.25 (#4160)
To not produce duplicating deps in Rerun
(https://github.com/rerun-io/rerun/pull/5280) I suggest we wait with
merging this until these crates have updated to `image` 0.25:
* [x] [`arboard`](https://crates.io/crates/arboard)
* [x] [`gltf`](https://crates.io/crates/gltf)
2024-05-13 13:35:15 +02:00

63 lines
1.7 KiB
Rust

//! Helpers for loading [`egui::IconData`].
use egui::IconData;
/// Helpers for working with [`IconData`].
pub trait IconDataExt {
/// Convert into [`image::RgbaImage`]
///
/// # Errors
/// If `width*height != 4 * rgba.len()`, or if the image is too big.
fn to_image(&self) -> Result<image::RgbaImage, String>;
/// Encode as PNG.
///
/// # Errors
/// The image is invalid, or the PNG encoder failed.
fn to_png_bytes(&self) -> Result<Vec<u8>, String>;
}
/// Load the contents of .png file.
///
/// # Errors
/// If this is not a valid png.
pub fn from_png_bytes(png_bytes: &[u8]) -> Result<IconData, image::ImageError> {
crate::profile_function!();
let image = image::load_from_memory(png_bytes)?;
Ok(from_image(image))
}
fn from_image(image: image::DynamicImage) -> IconData {
let image = image.into_rgba8();
IconData {
width: image.width(),
height: image.height(),
rgba: image.into_raw(),
}
}
impl IconDataExt for IconData {
fn to_image(&self) -> Result<image::RgbaImage, String> {
crate::profile_function!();
let Self {
rgba,
width,
height,
} = self.clone();
image::RgbaImage::from_raw(width, height, rgba).ok_or_else(|| "Invalid IconData".to_owned())
}
fn to_png_bytes(&self) -> Result<Vec<u8>, String> {
crate::profile_function!();
let image = self.to_image()?;
let mut png_bytes: Vec<u8> = Vec::new();
image
.write_to(
&mut std::io::Cursor::new(&mut png_bytes),
image::ImageFormat::Png,
)
.map_err(|err| err.to_string())?;
Ok(png_bytes)
}
}