
use image::{RgbaImage, ExtendedColorType, ImageEncoder, load_from_memory};
use image::codecs::png::PngEncoder;

pub fn save_to_memory_png(p: &RgbaImage) -> Result<Vec<u8>, String> {
	let (width, height) = p.dimensions();
	let mut blob = Vec::<u8>::new();
	let png_encoder = PngEncoder::new(&mut blob);
	match png_encoder.write_image(p, width, height, ExtendedColorType::Rgba8) {
		Ok(()) => Ok(blob),
		Err(_) => Err("Failed to encode text png".to_string()),
	}
}

pub fn ensure_32_bit_png(p: &[u8]) -> Result<Vec<u8>, String> {
	let img = match load_from_memory(p) {
		Ok(i) => i,
		Err(e) => return Err(format!("Failed to load png: {e}")),
	};
	save_to_memory_png(&img.into_rgba8())
}
