1

So far, the only way i've found to do this is

In order to display an image in rust using egui, I have to

  1. Use the image crate to read in a DynamicImage from a file
  2. Convert that DynamicImage to an ImageBuffer
  3. Convert that ImageBuffer into a FlatSamples<&[u8]>
  4. Convert that FlatSamples to a ColorImage
  5. Convert that ColorImage into an instance of ImageData
  6. Create a TextureHandle from that ImageData
  7. Create an egui image widget from that TextureHandle
  8. Add the widget to my ui

This was a massive headache to figure out.

Heres the code for how I did it

use egui::ImageData;
use std::path::Path;

pub fn get_image(filepath: &str, ix: u32, iy: u32, iw: u32, ih: u32) -> ImageData {
    let fp = Path::new(filepath);
    let color_image = load_image_from_path(&fp).unwrap();
    let img = ImageData::from(color_image);
    img
}

fn load_image_from_path(path: &std::path::Path) -> Result<egui::ColorImage, image::ImageError> {
    let image = image::io::Reader::open(path)?.decode()?;
    let size = [image.width() as _, image.height() as _];
    let image_buffer = image.to_rgba8();
    let pixels = image_buffer.as_flat_samples();
    Ok(egui::ColorImage::from_rgba_unmultiplied(
        size,
        pixels.as_slice(),
    ))
}

//inside my update function
            let img = ui.ctx().load_texture(
                "my-image",
                get_image("./image.png", 0, 0, 100, 100),
                Default::default()
            );

            ui.add(egui::Image::new(&img, img.size_vec2()));

Is there any simpler way to do this?

cafce25
  • 15,907
  • 4
  • 25
  • 31
Dr. Slate
  • 31
  • 4

1 Answers1

1

There's an example in the egui repo using egui_extras::RetainedImage. The only difference is that the example embeds the image data in the program while you want to read it from a file. So this should do it:

use egui_extras::image::RetainedImage;
use std::fs::File;

// During init:
let mut buffer = vec![];
File::open (filename)?.read_to_end (&mut buffer)?;
self.image = RetainedImage::from_image_bytes (filename, &buffer[..])?;

// Inside update:
self.image.show(ui);
Jmb
  • 18,893
  • 2
  • 28
  • 55