png conversion

This commit is contained in:
2026-03-06 12:43:34 +01:00
parent d125ba38b2
commit 51f6b5bfab
8 changed files with 2120 additions and 37 deletions

View File

@ -1,4 +1,7 @@
use std::time::SystemTime;
use arboard::{Clipboard, ImageData};
use image::codecs::png::{PngDecoder, PngEncoder};
use image::{ColorType, DynamicImage, ExtendedColorType, ImageEncoder, RgbaImage};
use std::{error::Error, time::SystemTime};
pub struct ClipboardEntry {
pub content: ClipboardData,
@ -10,21 +13,52 @@ pub enum ClipboardData {
Image(Vec<u8>), // png storage
}
pub trait ImageDataExt {
fn to_png(&self) -> Result<Vec<u8>, Box<dyn Error>>;
}
impl ImageDataExt for ImageData<'_> {
fn to_png(&self) -> Result<Vec<u8>, Box<dyn Error>> {
let mut buffer = Vec::new();
let encoder = PngEncoder::new(&mut buffer);
encoder.write_image(
&self.bytes,
self.width as u32,
self.height as u32,
ExtendedColorType::Rgba8,
)?;
Ok(buffer)
}
}
impl ClipboardData {
fn is_text(&self) -> bool {
pub fn is_text(&self) -> bool {
match self {
ClipboardData::Text(_) => true,
ClipboardData::Image(_) => false,
}
}
fn is_image(&self) -> bool {
pub fn is_image(&self) -> bool {
!self.is_text()
}
}
impl ClipboardEntry {
fn new() -> ClipboardData {
unimplemented!()
pub fn new(clipboard: &mut Clipboard) -> Result<ClipboardEntry, Box<dyn Error>> {
let clipboard_data_opt: Option<ClipboardData> = match clipboard.get_text() {
Ok(text) => Some(ClipboardData::Text(text)),
Err(_) => match clipboard.get_image() {
Ok(image) => Some(ClipboardData::Image(image.to_png()?)),
Err(_) => None,
},
};
let Some(clipboard_data) = clipboard_data_opt else {
return Err("Clipboard empty".into());
};
Ok(ClipboardEntry {
content: clipboard_data,
timestamp: SystemTime::now(),
})
}
}