You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Rust的egui库:从文件路径显示图片的最简方法?

简化Rust中egui显示图片的实现方法

原生的图片加载转换步骤确实繁琐,以下是两种更简便的实现方式:

方式一:使用egui_extras封装工具(推荐)

egui_extras提供了现成的图片加载器,可直接从文件路径生成TextureHandle,省去中间多层转换:

use egui_extras::image::ImageLoader;

// 在update函数内
let texture = ImageLoader::new(ui.ctx())
    .path("./image.png")
    .load()
    .expect("Failed to load image"); // 实际项目请合理处理错误

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

需在Cargo.toml中添加依赖:

egui_extras = { version = "0.22", features = ["image"] }

方式二:手动精简原有代码

若不想引入额外依赖,可合并转换逻辑,减少冗余函数:

use egui::{ColorImage, TextureHandle};
use std::path::Path;

fn load_texture(ctx: &egui::Context, path: &str) -> TextureHandle {
    let img = image::io::Reader::open(Path::new(path))
        .unwrap()
        .decode()
        .unwrap();
    let color_img = ColorImage::from_rgba_unmultiplied(
        [img.width() as _, img.height() as _],
        img.to_rgba8().as_flat_samples().as_slice(),
    );
    ctx.load_texture(path, color_img.into(), Default::default())
}

// 在update函数内
let img_texture = load_texture(ui.ctx(), "./image.png");
ui.add(egui::Image::new(&img_texture, img_texture.size_vec2()));

重要优化:避免重复加载

不要在每次update时重新加载纹理,会造成性能损耗。建议将TextureHandle存入App结构体,仅初始化一次:

struct MyApp {
    image_texture: Option<TextureHandle>,
}

impl Default for MyApp {
    fn default() -> Self {
        Self { image_texture: None }
    }
}

impl eframe::App for MyApp {
    fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
        egui::CentralPanel::default().show(ctx, |ui| {
            let img = self.image_texture.get_or_insert_with(|| {
                load_texture(ctx, "./image.png")
            });
            ui.add(egui::Image::new(img, img.size_vec2()));
        });
    }
}

内容的提问来源于stack exchange,提问作者Dr. Slate

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 04:17:30