use crate::{ColorName, InterlaceType, ImageResource, ImageConfig, compute_output_size_sharpen, fetch_magic_wand, magick_rust::{PixelWand, bindings}, starts_ends_with_caseless::EndsWithCaselessMultiple};
#[derive(Debug)]
pub struct JPGConfig {
pub width: u16,
pub height: u16,
pub shrink_only: bool,
pub sharpen: f64,
pub force_to_chroma_quartered: bool,
pub quality: u8,
pub background_color: Option<ColorName>,
pub ppi: f64,
}
impl JPGConfig {
pub fn new() -> JPGConfig {
JPGConfig {
width: 0u16,
height: 0u16,
shrink_only: true,
sharpen: -1f64,
force_to_chroma_quartered: true,
quality: 85u8,
background_color: None,
ppi: 72f64,
}
}
}
impl ImageConfig for JPGConfig {
fn get_width(&self) -> u16 {
self.width
}
fn get_height(&self) -> u16 {
self.height
}
fn get_sharpen(&self) -> f64 {
self.sharpen
}
fn is_shrink_only(&self) -> bool {
self.shrink_only
}
}
pub fn to_jpg(output: &mut ImageResource, input: &ImageResource, config: &JPGConfig) -> Result<(), &'static str> {
let (mut mw, vector) = fetch_magic_wand(input, config)?;
if let Some(background_color) = config.background_color {
let mut pw = PixelWand::new();
pw.set_color(background_color.as_str())?;
mw.set_image_background_color(&pw)?;
mw.set_image_alpha_channel(bindings::AlphaChannelOption_RemoveAlphaChannel)?;
}
if !vector {
let (width, height, sharpen) = compute_output_size_sharpen(&mw, config);
mw.resize_image(width as usize, height as usize, bindings::FilterType_LanczosFilter);
mw.sharpen_image(0f64, sharpen)?;
}
mw.profile_image("*", None)?;
if config.force_to_chroma_quartered {
mw.set_sampling_factors(&[2f64, 1f64, 1f64])?;
}
mw.set_image_compression_quality(config.quality.min(100) as usize)?;
mw.set_interlace_scheme(InterlaceType::LineInterlace.ordinal() as bindings::InterlaceType)?;
mw.set_image_format("JPEG")?;
if config.ppi >= 0f64 {
mw.set_image_resolution(config.ppi, config.ppi)?;
mw.set_image_units(bindings::ResolutionType_PixelsPerInchResolution)?;
}
match output {
ImageResource::Path(p) => {
if !p.ends_with_caseless_ascii_multiple(&[".jpg", ".jpeg"]) {
return Err("The file extension name is not jpg or jpeg.");
}
mw.write_image(p.as_str())?;
}
ImageResource::Data(b) => {
let mut temp = mw.write_image_blob("JPEG")?;
b.append(&mut temp);
}
ImageResource::MagickWand(mw_2) => {
*mw_2 = mw;
}
}
Ok(())
}