use std::collections::HashSet;
use jpeg_encoder::{ChromaSubsamplingMethod, ColorType, Encoder, SamplingFactor};
use super::{decode_image_with_format_limited, detect_image_mime_type, memoized, Conversion};
use crate::model::{image::ImageEffect, style::ImageFillMode};
use crate::paint::{ResolvedImageKind, ResolvedImagePayload};
use crate::renderer::render_tree::{BoundingBox, ImageNode};
pub(crate) fn print_jpeg_payload(
image: &ImageNode,
bbox: BoundingBox,
dpi: f64,
) -> Option<ResolvedImagePayload> {
if image.effect != ImageEffect::RealPic
|| image.brightness != 0
|| image.contrast != 0
|| image.opacity != 1.0
|| image.content_inset.is_some()
|| !matches!(
image.fill_mode,
None | Some(ImageFillMode::FitToSize | ImageFillMode::Total)
)
|| !dpi.is_finite()
|| dpi <= 0.0
{
return None;
}
let data = image.data.as_deref()?;
if super::png_sampling::pdf_source(data) {
return None;
}
match detect_image_mime_type(data) {
"image/bmp" | "image/png" | "image/gif" => (),
_ => return None,
}
let header = crate::renderer::image_header::canvaskit_encoded_image_header(data)
.filter(|header| header.is_within_decode_limits())?;
let (width, height) = (header.width, header.height);
if let Some(crop) = image.crop {
let source = crate::renderer::svg::compute_image_crop_src(
crop,
super::image_crop_reference(image),
f64::from(width),
f64::from(height),
);
if source != (0.0, 0.0, f64::from(width), f64::from(height)) {
return None;
}
}
let target = image.transform.effective_image_bbox(&bbox);
let nominal_width = (target.width * crate::renderer::DEFAULT_DPI / dpi).floor();
if !nominal_width.is_finite() || nominal_width <= 0.0 {
return None;
}
let quality = (75.0 * nominal_width / f64::from(width))
.floor()
.clamp(35.0, 75.0) as u8;
let expand = image.hancom2024_print_bitmap;
let bytes = encode_print_jpeg(data, quality, expand)?;
Some(ResolvedImagePayload {
data: bytes,
mime: "image/jpeg",
kind: ResolvedImageKind::OutputDevice,
suppress_effects: false,
})
}
pub(crate) fn encode_print_jpeg(data: &[u8], quality: u8, expand: bool) -> Option<Vec<u8>> {
if !(35..=75).contains(&quality) {
return None;
}
let format = match detect_image_mime_type(data) {
"image/bmp" => image::ImageFormat::Bmp,
"image/png" => image::ImageFormat::Png,
"image/gif" => image::ImageFormat::Gif,
_ => return None,
};
let header = crate::renderer::image_header::canvaskit_encoded_image_header(data)
.filter(|header| header.is_within_decode_limits())?;
let (width, height) = (header.width, header.height);
memoized(Conversion::PrintJpeg { quality, expand }, data, || {
let mut decoded = decode_image_with_format_limited(data, format)?.to_rgba8();
let mut colors = HashSet::with_capacity(1025);
for pixel in decoded.pixels() {
if pixel[3] != 255 {
return None;
}
if colors.len() <= 1024 {
colors.insert([pixel[0], pixel[1], pixel[2]]);
}
}
if colors.len() < 32 {
return None;
}
let quality = if expand {
super::print_codec::quality_for_palette(quality, colors.len())
} else {
quality
};
colors.extend([[0, 0, 0], [255, 255, 255]]);
let reconstruction = expand && colors.len() > 256;
if reconstruction {
const BAYER: [[u8; 4]; 4] =
[[0, 8, 2, 10], [12, 4, 14, 6], [3, 11, 1, 9], [15, 7, 13, 5]];
for (x, y, pixel) in decoded.enumerate_pixels_mut() {
for channel in &mut pixel.0[..3] {
let threshold =
BAYER[(y as usize + 4 - height as usize % 4) % 4][x as usize % 4];
let value = (*channel & 0xf8)
.saturating_add(u8::from(2 * (*channel & 7) > threshold) * 8)
.min(248);
*channel = value.saturating_add(value >> 5);
}
}
}
let rgb = image::DynamicImage::ImageRgba8(decoded).to_rgb8();
let mut output = Vec::new();
let mut encoder = Encoder::new(&mut output, quality);
encoder.set_sampling_factor(SamplingFactor::F_2_2);
encoder.set_chroma_subsampling_method(ChromaSubsamplingMethod::Average);
encoder
.encode(
rgb.as_raw(),
width.try_into().ok()?,
height.try_into().ok()?,
ColorType::Rgb,
)
.ok()?;
super::png_sampling::mark_print_jpeg(&mut output, reconstruction);
Some(output)
})
}