use std::io::Cursor;
use std::path::Path;
use base64::Engine;
use image::codecs::gif::{GifEncoder as GifWriter, Repeat};
use image::{Delay, DynamicImage, ExtendedColorType, ImageEncoder, ImageFormat, RgbImage, RgbaImage};
use crate::error::{ImageError, Result, invalid};
use crate::format::{FileExtension, Format, MediaType};
use crate::image::Image;
pub const DEFAULT_QUALITY: u8 = 75;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct EncoderOptions {
pub quality: Option<u8>,
pub progressive: Option<bool>,
pub interlaced: Option<bool>,
pub indexed: Option<bool>,
pub strip: Option<bool>,
}
impl EncoderOptions {
pub fn new() -> Self {
Self::default()
}
pub fn quality(mut self, quality: u8) -> Self {
self.quality = Some(quality);
self
}
pub fn progressive(mut self, progressive: bool) -> Self {
self.progressive = Some(progressive);
self
}
pub fn interlaced(mut self, interlaced: bool) -> Self {
self.interlaced = Some(interlaced);
self
}
pub fn indexed(mut self, indexed: bool) -> Self {
self.indexed = Some(indexed);
self
}
pub fn strip(mut self, strip: bool) -> Self {
self.strip = Some(strip);
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct JpegEncoder {
pub quality: u8,
pub progressive: bool,
pub strip: Option<bool>,
}
impl Default for JpegEncoder {
fn default() -> Self {
Self {
quality: DEFAULT_QUALITY,
progressive: false,
strip: None,
}
}
}
impl JpegEncoder {
pub fn new(quality: u8) -> Self {
Self {
quality,
..Self::default()
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PngEncoder {
pub interlaced: bool,
pub indexed: bool,
pub strip: Option<bool>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct GifEncoder {
pub interlaced: bool,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct BmpEncoder;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct IcoEncoder;
macro_rules! quality_encoder {
($($(#[$doc:meta])* $name:ident),*) => {$(
$(#[$doc])*
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct $name {
pub quality: u8,
pub strip: Option<bool>,
}
impl Default for $name {
fn default() -> Self {
Self { quality: DEFAULT_QUALITY, strip: None }
}
}
impl $name {
pub fn new(quality: u8) -> Self {
Self { quality, strip: None }
}
}
)*};
}
quality_encoder!(
WebpEncoder,
AvifEncoder,
TiffEncoder,
HeicEncoder,
Jpeg2000Encoder,
JxlEncoder
);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Encoder {
Avif(AvifEncoder),
Bmp(BmpEncoder),
Gif(GifEncoder),
Heic(HeicEncoder),
Ico(IcoEncoder),
Jpeg2000(Jpeg2000Encoder),
Jpeg(JpegEncoder),
Jxl(JxlEncoder),
Png(PngEncoder),
Tiff(TiffEncoder),
Webp(WebpEncoder),
}
macro_rules! into_encoder {
($($variant:ident($type:ident)),*) => {$(
impl From<$type> for Encoder {
fn from(encoder: $type) -> Self {
Encoder::$variant(encoder)
}
}
)*};
}
into_encoder!(
Avif(AvifEncoder),
Bmp(BmpEncoder),
Gif(GifEncoder),
Heic(HeicEncoder),
Ico(IcoEncoder),
Jpeg2000(Jpeg2000Encoder),
Jpeg(JpegEncoder),
Jxl(JxlEncoder),
Png(PngEncoder),
Tiff(TiffEncoder),
Webp(WebpEncoder)
);
impl Format {
pub fn encoder(self, options: EncoderOptions) -> Encoder {
let quality = options.quality.unwrap_or(DEFAULT_QUALITY);
let strip = options.strip;
match self {
Format::Avif => Encoder::Avif(AvifEncoder { quality, strip }),
Format::Bmp => Encoder::Bmp(BmpEncoder),
Format::Gif => Encoder::Gif(GifEncoder {
interlaced: options.interlaced.unwrap_or(false),
}),
Format::Heic => Encoder::Heic(HeicEncoder { quality, strip }),
Format::Ico => Encoder::Ico(IcoEncoder),
Format::Jp2 => Encoder::Jpeg2000(Jpeg2000Encoder { quality, strip }),
Format::Jpeg => Encoder::Jpeg(JpegEncoder {
quality,
progressive: options.progressive.unwrap_or(false),
strip,
}),
Format::Jxl => Encoder::Jxl(JxlEncoder { quality, strip }),
Format::Png => Encoder::Png(PngEncoder {
interlaced: options.interlaced.unwrap_or(false),
indexed: options.indexed.unwrap_or(false),
strip,
}),
Format::Tiff => Encoder::Tiff(TiffEncoder { quality, strip }),
Format::Webp => Encoder::Webp(WebpEncoder { quality, strip }),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EncodedImage {
bytes: Vec<u8>,
media_type: MediaType,
}
impl EncodedImage {
pub fn as_bytes(&self) -> &[u8] {
&self.bytes
}
pub fn into_bytes(self) -> Vec<u8> {
self.bytes
}
pub fn media_type(&self) -> &'static str {
self.media_type.value()
}
pub fn mimetype(&self) -> &'static str {
self.media_type()
}
pub fn size(&self) -> usize {
self.bytes.len()
}
pub fn to_data_uri(&self) -> String {
format!(
"data:{};base64,{}",
self.media_type(),
base64::engine::general_purpose::STANDARD.encode(&self.bytes)
)
}
pub fn save(&self, path: impl AsRef<Path>) -> Result<()> {
let path = path.as_ref();
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()
)));
}
std::fs::write(path, &self.bytes).map_err(|error| {
ImageError::FileNotWritable(format!("Can't write image to path \"{}\": {error}", path.display()))
})
}
}
impl AsRef<[u8]> for EncodedImage {
fn as_ref(&self) -> &[u8] {
&self.bytes
}
}
impl From<EncodedImage> for Vec<u8> {
fn from(encoded: EncodedImage) -> Self {
encoded.bytes
}
}
impl laravel::storage::Contents for EncodedImage {
fn into_bytes(self) -> laravel::storage::Bytes {
laravel::storage::Bytes::from(self.bytes)
}
}
impl laravel::storage::Contents for &EncodedImage {
fn into_bytes(self) -> laravel::storage::Bytes {
laravel::storage::Bytes::copy_from_slice(&self.bytes)
}
}
pub trait IntoMediaType {
fn into_media_type(self) -> Result<MediaType>;
}
impl IntoMediaType for MediaType {
fn into_media_type(self) -> Result<MediaType> {
Ok(self)
}
}
impl IntoMediaType for &str {
fn into_media_type(self) -> Result<MediaType> {
MediaType::from_value(self).ok_or_else(|| {
ImageError::NotSupported(format!(
"Unable to find encoder for unknown image media type \"{self}\""
))
})
}
}
impl IntoMediaType for &String {
fn into_media_type(self) -> Result<MediaType> {
self.as_str().into_media_type()
}
}
pub trait IntoFileExtension {
fn into_file_extension(self) -> Result<FileExtension>;
}
impl IntoFileExtension for FileExtension {
fn into_file_extension(self) -> Result<FileExtension> {
Ok(self)
}
}
impl IntoFileExtension for &str {
fn into_file_extension(self) -> Result<FileExtension> {
if self.is_empty() {
return Err(invalid("Unable to find file extension from empty string"));
}
FileExtension::from_value(&self.to_lowercase()).ok_or_else(|| {
ImageError::NotSupported(format!("Unable to find encoder for unknown file extension \"{self}\""))
})
}
}
impl IntoFileExtension for &String {
fn into_file_extension(self) -> Result<FileExtension> {
self.as_str().into_file_extension()
}
}
fn check_quality(quality: u8) -> Result<()> {
if quality > 100 {
return Err(invalid("Quality must be in range 0 to 100"));
}
Ok(())
}
fn encoder_error(error: impl std::fmt::Display) -> ImageError {
ImageError::Encoder(format!("Failed to encode image: {error}"))
}
impl Image {
pub fn encode(&self) -> Result<EncodedImage> {
let format = self
.origin()
.format()
.map_err(|_| ImageError::NotSupported("Unable to find encoder by unknown origin image format".into()))?;
self.encode_with(format.encoder(EncoderOptions::default()))
}
pub fn encode_with(&self, encoder: impl Into<Encoder>) -> Result<EncodedImage> {
let first = self.first();
let (bytes, media_type) = match encoder.into() {
Encoder::Jpeg(encoder) => {
check_quality(encoder.quality)?;
(self.encode_jpeg(encoder)?, MediaType::ImageJpeg)
}
Encoder::Png(_) => (write_image(first, ImageFormat::Png)?, MediaType::ImagePng),
Encoder::Gif(_) => (self.encode_gif()?, MediaType::ImageGif),
Encoder::Webp(encoder) => {
check_quality(encoder.quality)?;
(write_image(first, ImageFormat::WebP)?, MediaType::ImageWebp)
}
Encoder::Avif(encoder) => {
check_quality(encoder.quality)?;
(encode_avif(first, encoder.quality)?, MediaType::ImageAvif)
}
Encoder::Bmp(_) => (write_image(first, ImageFormat::Bmp)?, MediaType::ImageBmp),
Encoder::Tiff(encoder) => {
check_quality(encoder.quality)?;
(write_image(first, ImageFormat::Tiff)?, MediaType::ImageTiff)
}
Encoder::Ico(_) => (write_image(first, ImageFormat::Ico)?, MediaType::ImageXIcon),
Encoder::Heic(_) | Encoder::Jpeg2000(_) | Encoder::Jxl(_) => {
return Err(ImageError::NotSupported(
"The pure-Rust driver can't encode HEIC, JPEG 2000 or JPEG XL images".to_owned(),
));
}
};
Ok(EncodedImage { bytes, media_type })
}
pub fn encode_using_format(&self, format: Format, options: EncoderOptions) -> Result<EncodedImage> {
self.encode_with(format.encoder(options))
}
pub fn encode_using_media_type(
&self,
media_type: impl IntoMediaType,
options: EncoderOptions,
) -> Result<EncodedImage> {
self.encode_using_format(media_type.into_media_type()?.format(), options)
}
pub fn encode_using_file_extension(
&self,
extension: impl IntoFileExtension,
options: EncoderOptions,
) -> Result<EncodedImage> {
self.encode_using_format(extension.into_file_extension()?.format(), options)
}
pub fn encode_using_path(&self, path: impl AsRef<Path>, options: EncoderOptions) -> Result<EncodedImage> {
let path = path.as_ref();
let extension = path
.extension()
.and_then(|extension| extension.to_str())
.unwrap_or_default();
if extension.is_empty() {
return Err(invalid(format!(
"Unable to extract file extension from path \"{}\"",
path.display()
)));
}
self.encode_using_file_extension(extension, options)
}
pub fn save(&self, path: impl AsRef<Path>, options: EncoderOptions) -> Result<&Self> {
let path = path.as_ref();
if path.as_os_str().is_empty() {
return Err(invalid("Argument $path must not be an empty string"));
}
let encoded = match self.encode_using_path(path, options) {
Ok(encoded) => encoded,
Err(_) => {
let format = self.origin().format().map_err(|_| {
ImageError::NotSupported("Unable to find encoder by unknown origin image format".into())
})?;
self.encode_using_format(format, options)?
}
};
encoded.save(path)?;
Ok(self)
}
pub fn save_to_origin(&self, options: EncoderOptions) -> Result<&Self> {
let path = self
.origin()
.file_path()
.ok_or_else(|| ImageError::Encoder("Unable to determine path for saving".to_owned()))?
.to_path_buf();
self.save(path, options)
}
fn encode_jpeg(&self, encoder: JpegEncoder) -> Result<Vec<u8>> {
let background = self.config.background()?;
let first = self.first();
let (width, height) = first.dimensions();
let (Ok(w), Ok(h)) = (u16::try_from(width), u16::try_from(height)) else {
return Err(ImageError::Encoder(
"JPEG images can't be larger than 65535 pixels".to_owned(),
));
};
let mut rgb = RgbImage::new(width, height);
for (x, y, pixel) in first.enumerate_pixels() {
let alpha = f64::from(pixel[3]) / 255.0;
let mix = |c: u8, b: u8| (f64::from(c) * alpha + f64::from(b) * (1.0 - alpha)).round() as u8;
rgb.put_pixel(
x,
y,
image::Rgb([
mix(pixel[0], background.red),
mix(pixel[1], background.green),
mix(pixel[2], background.blue),
]),
);
}
let mut bytes = Vec::new();
let mut writer = jpeg_encoder::Encoder::new(&mut bytes, encoder.quality.max(1));
writer.set_progressive(encoder.progressive);
writer
.encode(rgb.as_raw(), w, h, jpeg_encoder::ColorType::Rgb)
.map_err(encoder_error)?;
Ok(bytes)
}
fn encode_gif(&self) -> Result<Vec<u8>> {
let mut bytes = Vec::new();
{
let mut writer = GifWriter::new(&mut bytes);
if self.is_animated() {
let repeat = if self.loops == 0 {
Repeat::Infinite
} else {
Repeat::Finite(self.loops)
};
writer.set_repeat(repeat).map_err(encoder_error)?;
let frames = self.frames.iter().map(|frame| {
image::Frame::from_parts(frame.buffer.clone(), 0, 0, Delay::from_saturating_duration(frame.delay))
});
writer.encode_frames(frames).map_err(encoder_error)?;
} else {
let first = self.first();
writer
.encode(first.as_raw(), first.width(), first.height(), ExtendedColorType::Rgba8)
.map_err(encoder_error)?;
}
}
Ok(bytes)
}
}
fn write_image(buffer: &RgbaImage, format: ImageFormat) -> Result<Vec<u8>> {
let mut cursor = Cursor::new(Vec::new());
if format == ImageFormat::Png {
image::codecs::png::PngEncoder::new(&mut cursor)
.write_image(
buffer.as_raw(),
buffer.width(),
buffer.height(),
ExtendedColorType::Rgba8,
)
.map_err(encoder_error)?;
} else {
DynamicImage::ImageRgba8(buffer.clone())
.write_to(&mut cursor, format)
.map_err(encoder_error)?;
}
Ok(cursor.into_inner())
}
#[cfg(feature = "avif")]
fn encode_avif(buffer: &RgbaImage, quality: u8) -> Result<Vec<u8>> {
let mut bytes = Vec::new();
image::codecs::avif::AvifEncoder::new_with_speed_quality(&mut bytes, 6, quality.max(1))
.write_image(
buffer.as_raw(),
buffer.width(),
buffer.height(),
ExtendedColorType::Rgba8,
)
.map_err(encoder_error)?;
Ok(bytes)
}
#[cfg(not(feature = "avif"))]
fn encode_avif(_: &RgbaImage, _: u8) -> Result<Vec<u8>> {
Err(ImageError::NotSupported(
"AVIF encoding needs the `avif` feature of laravel-image".to_owned(),
))
}