use std::borrow::Cow;
use std::io::Cursor;
use image::codecs::jpeg::JpegEncoder;
use image::imageops::FilterType;
use image::metadata::Orientation;
use image::{
DynamicImage, ImageDecoder, ImageEncoder, ImageFormat, ImageReader, Limits, Rgb, RgbImage,
};
pub const MAX_DIMENSION: u32 = 2000;
pub const DECODE_MAX_DIMENSION: u32 = 8192;
pub const DECODE_MAX_ALLOC: u64 = 320 * 1024 * 1024;
pub const QUALITIES: &[u8] = &[85, 75, 65, 55, 45];
const SCALE_STEPS: usize = 6;
const MIN_DIMENSION: u32 = 64;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Shrunk {
pub bytes: Vec<u8>,
pub width: u32,
pub height: u32,
pub source_width: u32,
pub source_height: u32,
pub quality: u8,
}
pub fn shrink(data: &[u8], max_bytes: usize, preserve_exif: bool) -> Result<Shrunk, String> {
let mut reader = ImageReader::new(Cursor::new(data))
.with_guessed_format()
.map_err(|error| format!("its format could not be read: {error}"))?;
match reader.format() {
Some(ImageFormat::Jpeg | ImageFormat::Png | ImageFormat::Gif | ImageFormat::WebP) => {}
Some(other) => {
return Err(format!(
"it is {}, which atpmcp does not shrink",
other.to_mime_type()
));
}
None => return Err("its format is not one atpmcp shrinks".to_string()),
}
let mut limits = Limits::default();
limits.max_image_width = Some(DECODE_MAX_DIMENSION);
limits.max_image_height = Some(DECODE_MAX_DIMENSION);
limits.max_alloc = Some(DECODE_MAX_ALLOC);
reader.limits(limits);
let undecodable = |error: image::ImageError| format!("it could not be decoded: {error}");
let mut decoder = reader.into_decoder().map_err(undecodable)?;
let orientation = decoder.orientation().unwrap_or(Orientation::NoTransforms);
let metadata = Metadata {
icc: decoder.icc_profile().ok().flatten(),
exif: if preserve_exif {
decoder.exif_metadata().ok().flatten().map(|mut exif| {
if exif.starts_with(b"Exif\0\0") {
exif.drain(..6);
}
let _ = Orientation::remove_from_exif_chunk(&mut exif);
exif
})
} else {
None
},
};
let mut image = DynamicImage::from_decoder(decoder).map_err(undecodable)?;
image.apply_orientation(orientation);
let (source_width, source_height) = (image.width(), image.height());
let mut bound = MAX_DIMENSION.min(source_width.max(source_height));
for _ in 0..=SCALE_STEPS {
let fitted = fit(&image, bound);
let rgb = onto_white(&fitted);
for &quality in QUALITIES {
let bytes = encode(&rgb, quality, &metadata)?;
if bytes.len() <= max_bytes {
return Ok(Shrunk {
bytes,
width: rgb.width(),
height: rgb.height(),
source_width,
source_height,
quality,
});
}
}
bound = bound * 3 / 4;
if bound < MIN_DIMENSION {
break;
}
}
Err(format!(
"it stays over {max_bytes} bytes even at {MIN_DIMENSION} pixels"
))
}
pub fn display_dimensions(data: &[u8]) -> Result<(u32, u32), String> {
let unreadable = |error: String| format!("its dimensions could not be read: {error}");
let mut reader = ImageReader::new(Cursor::new(data))
.with_guessed_format()
.map_err(|error| unreadable(error.to_string()))?;
let mut limits = Limits::default();
limits.max_image_width = Some(DECODE_MAX_DIMENSION);
limits.max_image_height = Some(DECODE_MAX_DIMENSION);
limits.max_alloc = Some(DECODE_MAX_ALLOC);
reader.limits(limits);
let mut decoder = reader
.into_decoder()
.map_err(|error| unreadable(error.to_string()))?;
let (width, height) = decoder.dimensions();
let turned = matches!(
decoder.orientation().unwrap_or(Orientation::NoTransforms),
Orientation::Rotate90
| Orientation::Rotate270
| Orientation::Rotate90FlipH
| Orientation::Rotate270FlipH
);
Ok(if turned {
(height, width)
} else {
(width, height)
})
}
fn fit(image: &DynamicImage, bound: u32) -> Cow<'_, DynamicImage> {
if image.width() <= bound && image.height() <= bound {
Cow::Borrowed(image)
} else {
Cow::Owned(image.resize(bound, bound, FilterType::CatmullRom))
}
}
fn onto_white(image: &DynamicImage) -> RgbImage {
if !image.color().has_alpha() {
return image.to_rgb8();
}
let rgba = image.to_rgba8();
let mut rgb = RgbImage::new(rgba.width(), rgba.height());
for (out, pixel) in rgb.pixels_mut().zip(rgba.pixels()) {
let [red, green, blue, alpha] = pixel.0;
let alpha = u32::from(alpha);
let blend = |channel: u8| {
let mixed = (u32::from(channel) * alpha + 255 * (255 - alpha) + 127) / 255;
u8::try_from(mixed).unwrap_or(u8::MAX)
};
*out = Rgb([blend(red), blend(green), blend(blue)]);
}
rgb
}
struct Metadata {
icc: Option<Vec<u8>>,
exif: Option<Vec<u8>>,
}
fn encode(rgb: &RgbImage, quality: u8, metadata: &Metadata) -> Result<Vec<u8>, String> {
let mut bytes = Vec::new();
let mut encoder = JpegEncoder::new_with_quality(&mut bytes, quality);
if let Some(icc) = &metadata.icc {
let _ = encoder.set_icc_profile(icc.clone());
}
if let Some(exif) = &metadata.exif {
let _ = encoder.set_exif_metadata(exif.clone());
}
encoder
.encode_image(rgb)
.map_err(|error| format!("it could not be encoded as JPEG: {error}"))?;
Ok(bytes)
}
#[cfg(test)]
pub(crate) mod tests {
use image::codecs::gif::GifEncoder;
use image::codecs::png::PngEncoder;
use image::{Delay, Frame, ImageEncoder, Rgba, RgbaImage};
use super::*;
pub(crate) fn noise(len: usize, seed: u64) -> Vec<u8> {
let mut state = seed | 1;
(0..len)
.map(|_| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
(state >> 32) as u8
})
.collect()
}
pub(crate) fn noise_png(width: u32, height: u32) -> Vec<u8> {
let pixels = noise((width * height * 3) as usize, u64::from(width * height));
let mut png = Vec::new();
PngEncoder::new(&mut png)
.write_image(&pixels, width, height, image::ExtendedColorType::Rgb8)
.expect("encode PNG");
png
}
fn decode(jpeg: &[u8]) -> DynamicImage {
image::load_from_memory_with_format(jpeg, ImageFormat::Jpeg).expect("a JPEG")
}
#[test]
fn noise_over_the_limit_comes_out_under_it() {
let png = noise_png(600, 400);
let limit = 60_000;
assert!(png.len() > limit);
let shrunk = shrink(&png, limit, false).expect("shrunk");
assert!(shrunk.bytes.len() <= limit, "{}", shrunk.bytes.len());
assert_eq!((shrunk.source_width, shrunk.source_height), (600, 400));
assert!(shrunk.width < 600);
let expected_height = shrunk.width * 2 / 3;
assert!(
shrunk.height.abs_diff(expected_height) <= 1,
"{}x{}",
shrunk.width,
shrunk.height
);
let decoded = decode(&shrunk.bytes);
assert_eq!(
(decoded.width(), decoded.height()),
(shrunk.width, shrunk.height)
);
}
#[test]
fn a_large_image_is_fitted_within_the_dimension_bound() {
let image = DynamicImage::ImageRgb8(RgbImage::from_fn(3000, 1000, |x, _| {
Rgb([(x % 256) as u8, 128, 64])
}));
let mut png = Vec::new();
image
.write_to(&mut Cursor::new(&mut png), ImageFormat::Png)
.expect("PNG");
let shrunk = shrink(&png, 1_000_000, false).expect("shrunk");
assert_eq!((shrunk.width, shrunk.height), (2000, 667));
assert_eq!(shrunk.quality, QUALITIES[0]);
}
#[test]
fn a_small_image_is_never_enlarged() {
let image = DynamicImage::ImageRgb8(RgbImage::from_pixel(40, 30, Rgb([10, 20, 30])));
let mut png = Vec::new();
image
.write_to(&mut Cursor::new(&mut png), ImageFormat::Png)
.expect("PNG");
let shrunk = shrink(&png, 1_000_000, false).expect("shrunk");
assert_eq!((shrunk.width, shrunk.height), (40, 30));
}
#[test]
fn transparency_goes_onto_white() {
let image = RgbaImage::from_fn(16, 16, |x, _| {
if x < 8 {
Rgba([0, 0, 0, 0])
} else {
Rgba([0, 0, 255, 255])
}
});
let mut png = Vec::new();
DynamicImage::ImageRgba8(image)
.write_to(&mut Cursor::new(&mut png), ImageFormat::Png)
.expect("PNG");
let decoded = decode(&shrink(&png, 1_000_000, false).expect("shrunk").bytes).to_rgb8();
let clear = decoded.get_pixel(2, 8).0;
assert!(clear.iter().all(|&c| c > 240), "{clear:?}");
let opaque = decoded.get_pixel(13, 8).0;
assert!(opaque[2] > 200 && opaque[0] < 60, "{opaque:?}");
}
#[test]
fn an_animated_gif_gives_its_first_frame() {
let frame = |colour: [u8; 4]| {
Frame::from_parts(
RgbaImage::from_pixel(8, 8, Rgba(colour)),
0,
0,
Delay::from_numer_denom_ms(100, 1),
)
};
let mut gif = Vec::new();
GifEncoder::new(&mut gif)
.encode_frames([frame([255, 0, 0, 255]), frame([0, 255, 0, 255])])
.expect("GIF");
let decoded = decode(&shrink(&gif, 1_000_000, false).expect("shrunk").bytes).to_rgb8();
let pixel = decoded.get_pixel(4, 4).0;
assert!(pixel[0] > 200 && pixel[1] < 60, "{pixel:?}");
}
#[test]
fn exif_orientation_is_applied() {
let exif = [
b'I', b'I', 42, 0, 8, 0, 0, 0, 1, 0, 0x12, 0x01, 3, 0, 1, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0,
0,
];
let mut jpeg = Vec::new();
let mut encoder = JpegEncoder::new_with_quality(&mut jpeg, 90);
encoder.set_exif_metadata(exif.to_vec()).expect("EXIF");
encoder
.encode_image(&RgbImage::from_pixel(40, 20, Rgb([200, 100, 50])))
.expect("JPEG");
let shrunk = shrink(&jpeg, 1_000_000, false).expect("shrunk");
assert_eq!((shrunk.width, shrunk.height), (20, 40));
}
#[test]
fn exif_is_copied_only_when_preserved_and_the_profile_always() {
use crate::image_metadata::tests::{ICC, SECRET, jpeg_with_metadata};
let contains = |haystack: &[u8], needle: &[u8]| {
haystack
.windows(needle.len())
.any(|window| window == needle)
};
let source = jpeg_with_metadata(6);
let stripped = shrink(&source, 1_000_000, false).expect("shrunk");
assert!(!contains(&stripped.bytes, SECRET));
assert!(!contains(&stripped.bytes, b"Exif\0\0"));
assert!(contains(&stripped.bytes, ICC));
let kept = shrink(&source, 1_000_000, true).expect("shrunk");
assert!(contains(&kept.bytes, SECRET), "the source's EXIF is copied");
assert!(contains(&kept.bytes, ICC));
let mut decoder = ImageReader::new(Cursor::new(&kept.bytes))
.with_guessed_format()
.unwrap()
.into_decoder()
.unwrap();
assert_eq!(decoder.orientation().unwrap(), Orientation::NoTransforms);
assert_eq!((kept.width, kept.height), (16, 24));
}
#[test]
fn display_dimensions_follow_the_exif_orientation() {
use crate::image_metadata::tests::jpeg_with_metadata;
assert_eq!(display_dimensions(&jpeg_with_metadata(1)), Ok((24, 16)));
assert_eq!(display_dimensions(&jpeg_with_metadata(6)), Ok((16, 24)));
assert_eq!(display_dimensions(&jpeg_with_metadata(3)), Ok((24, 16)));
assert!(display_dimensions(b"not an image").is_err());
}
#[test]
fn claimed_dimensions_over_the_cap_are_refused() {
let mut png = Vec::new();
DynamicImage::ImageRgb8(RgbImage::new(1, 1))
.write_to(&mut Cursor::new(&mut png), ImageFormat::Png)
.expect("PNG");
png[16..20].copy_from_slice(&20_000u32.to_be_bytes());
png[20..24].copy_from_slice(&20_000u32.to_be_bytes());
let crc = crc32(&png[12..29]);
png[29..33].copy_from_slice(&crc.to_be_bytes());
let error = shrink(&png, 1_000_000, false).expect_err("refused");
assert!(error.starts_with("it could not be decoded"), "{error}");
}
#[test]
fn a_format_it_does_not_shrink_is_refused() {
let mut bmp = Vec::new();
DynamicImage::ImageRgb8(RgbImage::new(2, 2))
.write_to(&mut Cursor::new(&mut bmp), ImageFormat::Bmp)
.unwrap_or_else(|_| bmp.extend_from_slice(b"BM\x46\0\0\0\0\0\0\0\x36\0\0\0"));
let error = shrink(&bmp, 1_000_000, false).expect_err("refused");
assert!(error.contains("does not shrink"), "{error}");
let error = shrink(b"not an image at all", 1_000_000, false).expect_err("refused");
assert!(error.contains("not one atpmcp shrinks"), "{error}");
}
pub(crate) fn crc32(bytes: &[u8]) -> u32 {
let mut crc = 0xFFFF_FFFFu32;
for &byte in bytes {
crc ^= u32::from(byte);
for _ in 0..8 {
crc = if crc & 1 == 1 {
(crc >> 1) ^ 0xEDB8_8320
} else {
crc >> 1
};
}
}
!crc
}
}