Files
sorsfonalak/services/backend/src/photo.rs
T

112 lines
4.6 KiB
Rust
Raw Normal View History

//! Uploaded photos: one stored version per photo, an upright JPEG at most
//! [`MAX_SIDE`] pixels on its longer side. Sized versions are made on request
//! by the frontend's image optimizer, so nothing else is stored.
//!
//! Re-encoding also drops the metadata of the original (EXIF: camera, place).
use std::io::Cursor;
use image::codecs::jpeg::JpegEncoder;
use image::imageops::FilterType;
use image::metadata::Orientation;
use image::{DynamicImage, ImageDecoder, ImageFormat, ImageReader, Limits};
/// The longer side of the stored photo, in pixels.
pub const MAX_SIDE: u32 = 2000;
/// The largest upload accepted, in bytes.
pub const MAX_UPLOAD: usize = 15 * 1024 * 1024;
/// The smallest photo worth showing (shorter side, in pixels).
const MIN_SIDE: u32 = 200;
const QUALITY: u8 = 86;
pub struct Photo {
pub jpeg: Vec<u8>,
pub width: u32,
pub height: u32,
}
impl std::fmt::Debug for Photo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Photo({}×{}, {} bytes)", self.width, self.height, self.jpeg.len())
}
}
/// A JPEG, PNG or WebP image made upright, at most [`MAX_SIDE`] pixels, as JPEG.
/// The error is a message for the uploader.
pub fn normalize(bytes: &[u8]) -> Result<Photo, String> {
let unreadable = || "A képet nem sikerült beolvasni. JPEG, PNG vagy WebP fotót tölts fel.".to_string();
let mut reader = ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|_| unreadable())?;
if !matches!(reader.format(), Some(ImageFormat::Jpeg | ImageFormat::Png | ImageFormat::WebP)) {
return Err(unreadable());
}
let mut limits = Limits::default();
limits.max_image_width = Some(12_000);
limits.max_image_height = Some(12_000);
reader.limits(limits);
let mut decoder = reader.into_decoder().map_err(|_| unreadable())?;
let orientation = decoder.orientation().unwrap_or(Orientation::NoTransforms);
let mut img = DynamicImage::from_decoder(decoder).map_err(|_| unreadable())?;
img.apply_orientation(orientation);
if img.width().min(img.height()) < MIN_SIDE {
return Err(format!("A kép túl kicsi: legalább {MIN_SIDE}×{MIN_SIDE} pixeles fotót tölts fel."));
}
if img.width().max(img.height()) > MAX_SIDE {
img = img.resize(MAX_SIDE, MAX_SIDE, FilterType::Lanczos3);
}
// JPEG has no transparency: a transparent PNG gets the site's dark background.
let rgb = flatten(img);
let mut jpeg = Vec::new();
JpegEncoder::new_with_quality(&mut jpeg, QUALITY).encode_image(&rgb).map_err(|e| e.to_string())?;
Ok(Photo { jpeg, width: rgb.width(), height: rgb.height() })
}
fn flatten(img: DynamicImage) -> image::RgbImage {
if !img.color().has_alpha() {
return img.to_rgb8();
}
let rgba = img.to_rgba8();
let background = [13u16, 18, 32];
image::RgbImage::from_fn(rgba.width(), rgba.height(), |x, y| {
let [r, g, b, a] = rgba.get_pixel(x, y).0;
let mix = |c: u8, bg: u16| ((u16::from(c) * u16::from(a) + bg * (255 - u16::from(a))) / 255) as u8;
image::Rgb([mix(r, background[0]), mix(g, background[1]), mix(b, background[2])])
})
}
#[cfg(test)]
mod tests {
use super::*;
fn png(width: u32, height: u32, alpha: bool) -> Vec<u8> {
let img = if alpha {
DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(width, height, image::Rgba([200, 100, 50, 0])))
} else {
DynamicImage::ImageRgb8(image::RgbImage::from_pixel(width, height, image::Rgb([200, 100, 50])))
};
let mut out = Vec::new();
img.write_to(&mut Cursor::new(&mut out), ImageFormat::Png).unwrap();
out
}
#[test]
fn makes_a_bounded_jpeg() {
let photo = normalize(&png(3000, 1500, false)).unwrap();
assert_eq!((photo.width, photo.height), (2000, 1000));
assert_eq!(&photo.jpeg[..3], &[0xFF, 0xD8, 0xFF], "a JPEG");
let small = normalize(&png(400, 600, true)).unwrap();
assert_eq!((small.width, small.height), (400, 600));
// a fully transparent pixel takes the background colour
let back = image::load_from_memory(&small.jpeg).unwrap().to_rgb8();
let [r, g, b] = back.get_pixel(10, 10).0;
assert!(r < 30 && g < 30 && b < 45, "{r} {g} {b}");
}
#[test]
fn rejects_what_is_not_a_photo() {
assert!(normalize(b"not an image at all").unwrap_err().contains("JPEG, PNG vagy WebP"));
assert!(normalize(&png(150, 900, false)).unwrap_err().contains("túl kicsi"));
// a GIF is a format we do not take
assert!(normalize(b"GIF89a\x01\x00\x01\x00\x00\x00\x00;").is_err());
}
}