Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add save button to twix #1665

Merged
merged 8 commits into from
Mar 9, 2025
Merged
48 changes: 47 additions & 1 deletion tools/twix/src/panels/image/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::sync::Arc;
use std::{env::temp_dir, fs::create_dir_all, sync::Arc, time::SystemTime};

use chrono::{DateTime, Utc};
use color_eyre::{eyre::eyre, Result};
Expand All @@ -7,6 +7,7 @@ use eframe::egui::{ColorImage, Response, SizeHint, TextureOptions, Ui, UiBuilder
use geometry::rectangle::Rectangle;
use image::RgbImage;
use linear_algebra::{point, vector};
use log::{info, warn};
use serde_json::{json, Value};

use types::{jpeg::JpegImage, ycbcr422_image::YCbCr422Image};
Expand Down Expand Up @@ -91,6 +92,40 @@ impl Panel for ImagePanel {
}
}

fn absolute_time_to_time_string(time: SystemTime) -> String {
DateTime::<Utc>::from(time)
.format("%H:%M:%S%.3f")
.to_string()
}

fn save_jpeg_image(buffer: &BufferHandle<JpegImage>, vision_cycler_name: String) -> Result<()> {
let now = SystemTime::now();
let time_stamp = absolute_time_to_time_string(now);
let buffer = buffer
.get_last_value()?
.ok_or_else(|| eyre!("no image available"))?;
let directory = temp_dir().join("twix");
create_dir_all(&directory)?;
let path = directory.join(format!("image_{vision_cycler_name}_{time_stamp}.jpeg"));
image::save_buffer(&path, &buffer.data, 640, 480, image::ColorType::Rgb8)?;
info!("image saved to '{}'", path.display());
Ok(())
}

fn save_raw_image(buffer: &BufferHandle<YCbCr422Image>, vision_cycler_name: String) -> Result<()> {
let now = SystemTime::now();
let time_stamp = absolute_time_to_time_string(now);
let buffer = buffer
.get_last_value()?
.ok_or_else(|| eyre!("no image available"))?;
let directory = temp_dir().join("twix");
create_dir_all(&directory)?;
let path = directory.join(format!("image_{vision_cycler_name}_{time_stamp}.png"));
buffer.save_to_ycbcr_444_file(&path)?;
info!("image saved to '{}'", path.display());
Ok(())
}

impl Widget for &mut ImagePanel {
fn ui(self, ui: &mut Ui) -> Response {
ui.horizontal(|ui| {
Expand All @@ -112,6 +147,17 @@ impl Widget for &mut ImagePanel {
let date: DateTime<Utc> = timestamp.into();
ui.label(date.format("%T%.3f").to_string());
}
if ui.button("Save").clicked() {
let result = match &self.image_buffer {
RawOrJpeg::Raw(buffer) => save_raw_image(buffer, format!("{:?}", self.cycler)),
RawOrJpeg::Jpeg(buffer) => {
save_jpeg_image(buffer, format!("{:?}", self.cycler))
}
};
if let Err(error) = result {
warn!("failed to save image: {error}");
}
}
});
let (response, mut painter) = TwixPainter::allocate(
ui,
Expand Down