use std::io::Cursor;
use std::path::{Path, PathBuf};
use std::time::Duration;
use base64::Engine;
use image::{AnimationDecoder, ImageDecoder, ImageFormat, RgbaImage};
use crate::config::{DriverConfig, current};
use crate::encoders::EncodedImage;
use crate::error::{ImageError, Result};
use crate::exif::Exif;
use crate::format::MediaType;
use crate::image::{Frame, Image, Origin};
#[derive(Debug, Clone)]
pub enum Source {
Text(String),
Path(PathBuf),
Binary(Vec<u8>),
Image(Box<Image>),
}
impl From<&str> for Source {
fn from(value: &str) -> Self {
Source::Text(value.to_owned())
}
}
impl From<String> for Source {
fn from(value: String) -> Self {
Source::Text(value)
}
}
impl From<&String> for Source {
fn from(value: &String) -> Self {
Source::Text(value.clone())
}
}
impl From<&Path> for Source {
fn from(value: &Path) -> Self {
Source::Path(value.to_path_buf())
}
}
impl From<PathBuf> for Source {
fn from(value: PathBuf) -> Self {
Source::Path(value)
}
}
impl From<&PathBuf> for Source {
fn from(value: &PathBuf) -> Self {
Source::Path(value.clone())
}
}
impl From<Vec<u8>> for Source {
fn from(value: Vec<u8>) -> Self {
Source::Binary(value)
}
}
impl From<&Vec<u8>> for Source {
fn from(value: &Vec<u8>) -> Self {
Source::Binary(value.clone())
}
}
impl From<&[u8]> for Source {
fn from(value: &[u8]) -> Self {
Source::Binary(value.to_vec())
}
}
impl<const N: usize> From<&[u8; N]> for Source {
fn from(value: &[u8; N]) -> Self {
Source::Binary(value.to_vec())
}
}
impl From<laravel::storage::Bytes> for Source {
fn from(value: laravel::storage::Bytes) -> Self {
Source::Binary(value.to_vec())
}
}
impl From<&laravel::http::UploadedFile> for Source {
fn from(value: &laravel::http::UploadedFile) -> Self {
Source::Path(value.path().to_path_buf())
}
}
impl From<laravel::http::UploadedFile> for Source {
fn from(value: laravel::http::UploadedFile) -> Self {
Source::Path(value.path().to_path_buf())
}
}
impl From<Image> for Source {
fn from(value: Image) -> Self {
Source::Image(Box::new(value))
}
}
impl From<&Image> for Source {
fn from(value: &Image) -> Self {
Source::Image(Box::new(value.clone()))
}
}
impl From<EncodedImage> for Source {
fn from(value: EncodedImage) -> Self {
Source::Binary(value.into_bytes())
}
}
impl From<&EncodedImage> for Source {
fn from(value: &EncodedImage) -> Self {
Source::Binary(value.as_bytes().to_vec())
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ImageManager {
config: DriverConfig,
}
impl ImageManager {
pub fn new(config: DriverConfig) -> Self {
Self { config }
}
pub fn using_driver() -> Self {
Self::default()
}
pub fn configured() -> Self {
Self::new(current().options())
}
pub fn config(&self) -> &DriverConfig {
&self.config
}
pub fn create_image(&self, width: u32, height: u32) -> Result<Image> {
if width < 1 || height < 1 {
return Err(ImageError::InvalidArgument(
"Invalid image size. Must be int<1, max>".to_owned(),
));
}
let buffer = RgbaImage::from_pixel(width, height, image::Rgba([255, 255, 255, 0]));
Ok(Image::from_frames(
vec![Frame {
buffer,
delay: Duration::ZERO,
}],
self.config.clone(),
))
}
pub fn decode(&self, source: impl Into<Source>) -> Result<Image> {
match source.into() {
Source::Image(image) => Ok(*image),
Source::Binary(bytes) => self.decode_binary(bytes),
Source::Path(path) => self.decode_path(path),
Source::Text(text) => {
if text.is_empty() {
return Err(ImageError::InvalidArgument(
"Unable to decode from empty string".to_owned(),
));
}
if is_data_uri(&text) {
return self.decode_data_uri(&text);
}
if let Some(bytes) = base64_image(&text) {
return self.decode_binary(bytes);
}
self.decode_path(text)
}
}
}
pub fn decode_path(&self, path: impl AsRef<Path>) -> Result<Image> {
let path = path.as_ref();
let display = path.display();
let directory = path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or(Path::new("."));
if !directory.is_dir() {
return Err(ImageError::DirectoryNotFound(format!(
"Directory \"{}\" not found",
directory.display()
)));
}
if !path.is_file() {
return Err(ImageError::FileNotFound(format!("File \"{display}\" not found")));
}
let bytes = std::fs::read(path)
.map_err(|error| ImageError::FileNotReadable(format!("File \"{display}\" is not readable: {error}")))?;
let mut image = decode_bytes(&bytes, &self.config)?;
image.origin = Origin::new(media_type_of(&bytes)?, Some(path.to_path_buf()));
Ok(image)
}
pub fn decode_binary(&self, binary: impl AsRef<[u8]>) -> Result<Image> {
decode_bytes(binary.as_ref(), &self.config)
}
pub fn decode_base64(&self, base64: &str) -> Result<Image> {
let bytes = base64::engine::general_purpose::STANDARD
.decode(base64.trim())
.map_err(|_| ImageError::Decoder("Input is not Base64-encoded data".to_owned()))?;
self.decode_binary(bytes)
}
pub fn decode_data_uri(&self, data_uri: &str) -> Result<Image> {
let malformed = || ImageError::Decoder("Input is not a valid data URI".to_owned());
let rest = data_uri.strip_prefix("data:").ok_or_else(malformed)?;
let (meta, data) = rest.split_once(',').ok_or_else(malformed)?;
if meta.split(';').any(|part| part.eq_ignore_ascii_case("base64")) {
return self.decode_base64(data);
}
self.decode_binary(percent_decode(data))
}
pub fn decode_uploaded_file(&self, file: &laravel::http::UploadedFile) -> Result<Image> {
self.decode_path(file.path())
}
}
fn is_data_uri(text: &str) -> bool {
text.starts_with("data:") && text.contains(',')
}
fn base64_image(text: &str) -> Option<Vec<u8>> {
if text.len() < 8
|| !text
.trim()
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"+/=\r\n".contains(&b))
{
return None;
}
let bytes = base64::engine::general_purpose::STANDARD.decode(text.trim()).ok()?;
image::guess_format(&bytes).is_ok().then_some(bytes)
}
fn percent_decode(data: &str) -> Vec<u8> {
let bytes = data.as_bytes();
let mut decoded = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%'
&& i + 2 < bytes.len()
&& let Ok(hex) = std::str::from_utf8(&bytes[i + 1..i + 3])
&& let Ok(byte) = u8::from_str_radix(hex, 16)
{
decoded.push(byte);
i += 3;
continue;
}
decoded.push(bytes[i]);
i += 1;
}
decoded
}
pub(crate) fn media_type_of(bytes: &[u8]) -> Result<MediaType> {
let format = image::guess_format(bytes).map_err(|_| ImageError::Decoder("Unable to decode input".to_owned()))?;
Ok(match format {
ImageFormat::Jpeg => MediaType::ImageJpeg,
ImageFormat::Png => MediaType::ImagePng,
ImageFormat::Gif => MediaType::ImageGif,
ImageFormat::WebP => MediaType::ImageWebp,
ImageFormat::Avif => MediaType::ImageAvif,
ImageFormat::Bmp => MediaType::ImageBmp,
ImageFormat::Tiff => MediaType::ImageTiff,
ImageFormat::Ico => MediaType::ImageXIcon,
other => {
return Err(ImageError::NotSupported(format!(
"Unable to decode images of the format {other:?}"
)));
}
})
}
const MAX_DECODED_BYTES: u64 = 512 * 1024 * 1024;
pub(crate) fn decode_bytes(bytes: &[u8], config: &DriverConfig) -> Result<Image> {
let media_type = media_type_of(bytes)?;
let decode_error = |error: image::ImageError| match error {
image::ImageError::Unsupported(error) => ImageError::NotSupported(format!("Unable to decode input: {error}")),
error => ImageError::Decoder(format!("Unable to decode input: {error}")),
};
let mut loops = 0;
let frames = if media_type == MediaType::ImageGif && config.decode_animation {
let mut decoder = image::codecs::gif::GifDecoder::new(Cursor::new(bytes)).map_err(decode_error)?;
decoder.set_limits(image::Limits::default()).map_err(decode_error)?;
let mut frames = Vec::new();
let mut total: u64 = 0;
for frame in decoder.into_frames() {
let frame = frame.map_err(decode_error)?;
total = total.saturating_add(frame.buffer().len() as u64);
if total > MAX_DECODED_BYTES {
return Err(ImageError::Decoder(
"Unable to decode input: the animation's frames exceed the memory limit".to_owned(),
));
}
let (numerator, denominator) = frame.delay().numer_denom_ms();
let delay = Duration::from_micros(u64::from(numerator) * 1000 / u64::from(denominator.max(1)));
frames.push(Frame {
buffer: frame.into_buffer(),
delay,
});
}
loops = gif_loops(bytes);
frames
} else {
let format = image::guess_format(bytes).map_err(decode_error)?;
let decoded = image::load_from_memory_with_format(bytes, format).map_err(decode_error)?;
vec![Frame {
buffer: decoded.to_rgba8(),
delay: Duration::ZERO,
}]
};
let mut image = Image::from_frames(frames, config.clone());
image.loops = loops;
image.origin = Origin::new(media_type, None);
image.exif = Exif::read(bytes);
if config.auto_orientation {
image.orient();
}
Ok(image)
}
fn gif_loops(bytes: &[u8]) -> u16 {
let mut options = gif::DecodeOptions::new();
options.set_color_output(gif::ColorOutput::Indexed);
let Ok(mut decoder) = options.read_info(Cursor::new(bytes)) else {
return 0;
};
let _ = decoder.next_frame_info();
match decoder.repeat() {
gif::Repeat::Infinite => 0,
gif::Repeat::Finite(count) => count,
}
}