refactor: deduplicate into fn load_image
This commit is contained in:
parent
549c478a8c
commit
53f78d9588
1 changed files with 31 additions and 29 deletions
58
src/main.rs
58
src/main.rs
|
|
@ -1,4 +1,4 @@
|
|||
use std::{env, ffi::OsStr, fs};
|
||||
use std::{env, ffi::OsStr, fs, path::Path};
|
||||
|
||||
use iced::{
|
||||
Alignment, Color, Element, Length, Renderer, Subscription, Task, Theme, color, event,
|
||||
|
|
@ -15,7 +15,7 @@ enum Message {
|
|||
Event(iced::Event),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct State {
|
||||
image: Option<RgbaImage>,
|
||||
image_display: Option<widget::image::Allocation>,
|
||||
|
|
@ -24,20 +24,9 @@ struct State {
|
|||
}
|
||||
impl State {
|
||||
fn new() -> (Self, Task<Message>) {
|
||||
let state = State {
|
||||
image_display: None,
|
||||
image: env::args().nth(1).and_then(|path| {
|
||||
Some(
|
||||
ImageReader::open(path)
|
||||
.unwrap()
|
||||
.decode()
|
||||
.unwrap()
|
||||
.into_rgba8(),
|
||||
)
|
||||
}),
|
||||
let mut state = State::default();
|
||||
|
||||
error: None,
|
||||
};
|
||||
env::args().nth(1).and_then(|path| state.load_image(path));
|
||||
let allocate_image = state.allocate_image();
|
||||
|
||||
(state, allocate_image)
|
||||
|
|
@ -124,6 +113,31 @@ impl State {
|
|||
Task::none()
|
||||
}
|
||||
|
||||
fn load_image(&mut self, path: impl AsRef<Path>) -> Option<String> {
|
||||
let reader = match ImageReader::open(&path) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
return Some(format!(
|
||||
"failed to create reader for '{}': {e}",
|
||||
path.as_ref().display()
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
let decoded_image = match reader.decode() {
|
||||
Ok(i) => i,
|
||||
Err(e) => {
|
||||
return Some(format!(
|
||||
"failed to decode image '{}': {e}",
|
||||
path.as_ref().display()
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
self.image = Some(decoded_image.into_rgba8());
|
||||
|
||||
None
|
||||
}
|
||||
fn open_image(&mut self) -> Option<String> {
|
||||
let Some(path) = FileDialog::new()
|
||||
.add_filter(
|
||||
|
|
@ -138,19 +152,7 @@ impl State {
|
|||
return Some("no path to open provided".into());
|
||||
};
|
||||
|
||||
let reader = match ImageReader::open(path) {
|
||||
Ok(r) => r,
|
||||
Err(e) => return Some(format!("failed to create reader: {e}")),
|
||||
};
|
||||
|
||||
let decoded_image = match reader.decode() {
|
||||
Ok(i) => i,
|
||||
Err(e) => return Some(format!("failed to decode image: {e}")),
|
||||
};
|
||||
|
||||
self.image = Some(decoded_image.into_rgba8());
|
||||
|
||||
None
|
||||
self.load_image(path)
|
||||
}
|
||||
|
||||
fn save_image(&self) -> Option<String> {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue