This commit is contained in:
nora 2023-04-18 15:38:14 +02:00
parent 12163d1338
commit 550b1644cb
363 changed files with 84081 additions and 16 deletions

View file

@ -0,0 +1,18 @@
[package]
name = "download_image"
version = "0.1.0"
authors = ["Emil Ernerfeldt <emil.ernerfeldt@gmail.com>"]
license = "MIT OR Apache-2.0"
edition = "2021"
rust-version = "1.65"
publish = false
[dependencies]
eframe = { path = "../../crates/eframe", features = [
"__screenshot", # __screenshot is so we can dump a screenshot using EFRAME_SCREENSHOT_TO
] }
egui_extras = { path = "../../crates/egui_extras", features = ["image"] }
ehttp = "0.2"
image = { version = "0.24", default-features = false, features = ["jpeg"] }
poll-promise = "0.2"

View file

@ -0,0 +1,7 @@
Example how to download and show an image with eframe/egui.
```sh
cargo run -p download_image
```
![](screenshot.png)

Binary file not shown.

After

Width:  |  Height:  |  Size: 353 KiB

View file

@ -0,0 +1,64 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] // hide console window on Windows in release
use eframe::egui;
use egui_extras::RetainedImage;
use poll_promise::Promise;
fn main() -> Result<(), eframe::Error> {
let options = eframe::NativeOptions::default();
eframe::run_native(
"Download and show an image with eframe/egui",
options,
Box::new(|_cc| Box::new(MyApp::default())),
)
}
#[derive(Default)]
struct MyApp {
/// `None` when download hasn't started yet.
promise: Option<Promise<ehttp::Result<RetainedImage>>>,
}
impl eframe::App for MyApp {
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
let promise = self.promise.get_or_insert_with(|| {
// Begin download.
// We download the image using `ehttp`, a library that works both in WASM and on native.
// We use the `poll-promise` library to communicate with the UI thread.
let ctx = ctx.clone();
let (sender, promise) = Promise::new();
let request = ehttp::Request::get("https://picsum.photos/seed/1.759706314/1024");
ehttp::fetch(request, move |response| {
let image = response.and_then(parse_response);
sender.send(image); // send the results back to the UI thread.
ctx.request_repaint(); // wake up UI thread
});
promise
});
egui::CentralPanel::default().show(ctx, |ui| match promise.ready() {
None => {
ui.spinner(); // still loading
}
Some(Err(err)) => {
ui.colored_label(ui.visuals().error_fg_color, err); // something went wrong
}
Some(Ok(image)) => {
image.show_max_size(ui, ui.available_size());
}
});
}
}
#[allow(clippy::needless_pass_by_value)]
fn parse_response(response: ehttp::Response) -> Result<RetainedImage, String> {
let content_type = response.content_type().unwrap_or_default();
if content_type.starts_with("image/") {
RetainedImage::from_image_bytes(&response.url, &response.bytes)
} else {
Err(format!(
"Expected image, found content-type {:?}",
content_type
))
}
}