use image::DynamicImage::ImageRgba8;
use image::{GenericImageView, ImageBuffer};
use std::io;
use std::path::Path;
use crate::PhotonImage;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum Error {
#[error(transparent)]
ImageError(#[from] image::ImageError),
#[error(transparent)]
IoError(#[from] io::Error),
}
pub fn open_image<P>(img_path: P) -> Result<PhotonImage, Error>
where
P: AsRef<Path>,
{
let img = image::open(img_path)?;
let (width, height) = img.dimensions();
let raw_pixels = img.to_rgba8().to_vec();
Ok(PhotonImage {
raw_pixels,
width,
height,
})
}
pub fn open_image_from_bytes(buffer: &[u8]) -> Result<PhotonImage, Error> {
let img = image::load_from_memory(buffer)?;
let (width, height) = img.dimensions();
let raw_pixels = img.to_rgba8().to_vec();
Ok(PhotonImage {
raw_pixels,
width,
height,
})
}
pub fn save_image<P>(img: PhotonImage, img_path: P) -> Result<(), Error>
where
P: AsRef<Path>,
{
let raw_pixels = img.raw_pixels;
let width = img.width;
let height = img.height;
let img_buffer = ImageBuffer::from_vec(width, height, raw_pixels).unwrap();
let dynimage = ImageRgba8(img_buffer);
dynimage.save(img_path)?;
Ok(())
}
pub fn image_to_bytes(img: PhotonImage) -> Vec<u8> {
let raw_pixels = img.raw_pixels;
let width = img.width;
let height = img.height;
let img_buffer = ImageBuffer::from_vec(width, height, raw_pixels).unwrap();
let dynimage = ImageRgba8(img_buffer);
dynimage.into_bytes()
}