use taskdaemon_handler::{run, success, error, Task, Result};
use serde_json::{json, Value};
use base64::{Engine, engine::general_purpose::STANDARD};
use image::{ImageFormat, imageops::FilterType};
use std::io::Cursor;
fn resize_image(task: Task) -> Result<Value> {
let url = match task.task_data.get("image_url").and_then(|v| v.as_str()) {
Some(u) => u,
None => return error("missing image_url", false),
};
let width = match task.task_data.get("width").and_then(|v| v.as_u64()) {
Some(w) => w as u32,
None => return error("missing width", false),
};
let height = match task.task_data.get("height").and_then(|v| v.as_u64()) {
Some(h) => h as u32,
None => return error("missing height", false),
};
// Download
let response = match reqwest::blocking::get(url) {
Ok(r) => r,
Err(e) => return error(e.to_string(), true), // Retryable
};
let bytes = match response.bytes() {
Ok(b) => b,
Err(e) => return error(e.to_string(), true),
};
// Decode and resize
let img = match image::load_from_memory(&bytes) {
Ok(i) => i,
Err(e) => return error(e.to_string(), false),
};
let resized = img.resize_exact(width, height, FilterType::Lanczos3);
// Encode
let mut buf = Cursor::new(Vec::new());
if let Err(e) = resized.write_to(&mut buf, ImageFormat::Png) {
return error(e.to_string(), false);
}
let b64 = STANDARD.encode(buf.into_inner());
success(json!({
"data": b64,
"size": [width, height],
"format": "png"
}))
}
fn main() {
run(resize_image);
}