mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-26 03:50:17 +00:00
format: cut over thumbnail decode and image dimension probing to craft-image-codecs (#2528)
This commit is contained in:
@@ -160,3 +160,38 @@ fn a_hash_shaped_rest_image_ref_never_names_its_placeholder() {
|
||||
assert_eq!(doc.images.keys().collect::<Vec<_>>(), ["rest-image-missing"], "{image_ref}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_dimensions_preserve_stored_orientation_and_reject_corrupt() {
|
||||
let rgb = image::RgbImage::from_pixel(24, 16, image::Rgb([100, 150, 200]));
|
||||
let mut jpg = Vec::new();
|
||||
rgb.write_to(&mut std::io::Cursor::new(&mut jpg), image::ImageFormat::Jpeg).unwrap();
|
||||
let mut exif = b"Exif\0\0II\x2a\0\x08\0\0\0\x01\0\x12\x01\x03\0\x01\0\0\0".to_vec();
|
||||
exif.extend_from_slice(&6u16.to_le_bytes());
|
||||
exif.extend_from_slice(&[0; 6]);
|
||||
let mut oriented = jpg[..2].to_vec();
|
||||
oriented.extend_from_slice(&[0xff, 0xe1]);
|
||||
oriented.extend_from_slice(&u16::try_from(exif.len() + 2).unwrap().to_be_bytes());
|
||||
oriented.extend_from_slice(&exif);
|
||||
oriented.extend_from_slice(&jpg[2..]);
|
||||
|
||||
let mut d = Document::new("t");
|
||||
let (_, w, h) = add_image(&mut d, oriented.clone()).unwrap();
|
||||
assert_eq!((w, h), (24, 16));
|
||||
let data = image_data(oriented);
|
||||
assert_eq!((data.width, data.height), (24, 16));
|
||||
|
||||
let img = image::RgbaImage::from_pixel(9, 5, image::Rgba([1, 2, 3, 255]));
|
||||
for fmt in [image::ImageFormat::Png, image::ImageFormat::WebP, image::ImageFormat::Gif] {
|
||||
let mut bytes = Vec::new();
|
||||
img.write_to(&mut std::io::Cursor::new(&mut bytes), fmt).unwrap();
|
||||
let (_, w, h) = add_image(&mut d, bytes.clone()).unwrap();
|
||||
assert_eq!((w, h), (9, 5), "{fmt:?}");
|
||||
let data = image_data(bytes);
|
||||
assert_eq!((data.width, data.height), (9, 5), "{fmt:?}");
|
||||
}
|
||||
|
||||
assert!(add_image(&mut d, b"not an image".to_vec()).is_err());
|
||||
let bad = image_data(b"not an image".to_vec());
|
||||
assert_eq!((bad.width, bad.height), (0, 0));
|
||||
}
|
||||
|
||||
@@ -165,13 +165,18 @@ pub fn image_hash(bytes: &[u8]) -> String {
|
||||
d.iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
/// Stored pixel dimensions of encoded image `bytes` (without EXIF orientation swap).
|
||||
fn stored_dimensions(bytes: &[u8]) -> Result<(u32, u32), craft_image_codecs::CodecError> {
|
||||
match craft_image_codecs::probe_stored_size(bytes, &craft_image_codecs::Limits::default()) {
|
||||
Ok(dims) => Ok(dims),
|
||||
Err(craft_image_codecs::CodecError::Unsupported { .. }) => craft_image_codecs::probe_allocation_size(bytes),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Register encoded image bytes with the document; returns the hash and pixel size.
|
||||
pub fn add_image(doc: &mut Document, bytes: Vec<u8>) -> Result<(String, u32, u32), FormatError> {
|
||||
let (w, h) = image::ImageReader::new(std::io::Cursor::new(&bytes))
|
||||
.with_guessed_format()
|
||||
.map_err(|e| FormatError::Corrupt(e.to_string()))?
|
||||
.into_dimensions()
|
||||
.map_err(|e| FormatError::Corrupt(format!("unsupported image: {e}")))?;
|
||||
let (w, h) = stored_dimensions(&bytes).map_err(|e| FormatError::Corrupt(format!("unsupported image: {e}")))?;
|
||||
let hash = image_hash(&bytes);
|
||||
doc.images.insert(hash.clone(), ImageData { bytes: Arc::new(bytes), width: w, height: h });
|
||||
Ok((hash, w, h))
|
||||
@@ -179,8 +184,7 @@ pub fn add_image(doc: &mut Document, bytes: Vec<u8>) -> Result<(String, u32, u32
|
||||
|
||||
/// Image bytes with their pixel size (0×0 when they can't be decoded).
|
||||
pub(crate) fn image_data(data: Vec<u8>) -> ImageData {
|
||||
let (w, h) =
|
||||
image::ImageReader::new(std::io::Cursor::new(&data)).with_guessed_format().ok().and_then(|r| r.into_dimensions().ok()).unwrap_or((0, 0));
|
||||
let (w, h) = stored_dimensions(&data).unwrap_or((0, 0));
|
||||
ImageData { bytes: Arc::new(data), width: w, height: h }
|
||||
}
|
||||
|
||||
|
||||
@@ -43,20 +43,26 @@ pub fn decode_thumbnail(bytes: &[u8], fit: u32) -> Option<Thumbnail> {
|
||||
if crate::jpeg::finer_than_first(bytes) {
|
||||
return None;
|
||||
}
|
||||
let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?;
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_image_width = Some(MAX_THUMBNAIL_SIDE);
|
||||
limits.max_image_height = Some(MAX_THUMBNAIL_SIDE);
|
||||
limits.max_alloc = Some(MAX_DECODE_ALLOC);
|
||||
reader.limits(limits);
|
||||
let mut picture = reader.decode().ok()?;
|
||||
let fit = fit.clamp(1, MAX_THUMBNAIL_SIDE);
|
||||
if picture.width() > fit || picture.height() > fit {
|
||||
picture = picture.thumbnail(fit, fit);
|
||||
let opts = craft_image_codecs::DecodeOptions {
|
||||
limits: craft_image_codecs::Limits::new(MAX_THUMBNAIL_SIDE, MAX_THUMBNAIL_SIDE, u64::MAX, MAX_DECODE_ALLOC),
|
||||
keep_orientation: true,
|
||||
};
|
||||
let img = craft_image_codecs::decode_with(bytes, &opts).ok()?;
|
||||
let rgba_img = img.converted(craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8);
|
||||
let (w, h) = rgba_img.dimensions();
|
||||
if w == 0 || h == 0 {
|
||||
return None;
|
||||
}
|
||||
let rgba = picture.to_rgba8();
|
||||
let (width, height) = rgba.dimensions();
|
||||
(width > 0 && height > 0).then(|| Thumbnail { width, height, rgba: rgba.into_raw() })
|
||||
let fit = fit.clamp(1, MAX_THUMBNAIL_SIDE);
|
||||
let (width, height, rgba) = if w > fit || h > fit {
|
||||
let buf = image::RgbaImage::from_raw(w, h, rgba_img.into_owned().into_data())?;
|
||||
let thumb = image::DynamicImage::ImageRgba8(buf).thumbnail(fit, fit).into_rgba8();
|
||||
let (nw, nh) = thumb.dimensions();
|
||||
(nw, nh, thumb.into_raw())
|
||||
} else {
|
||||
(w, h, rgba_img.into_owned().into_data())
|
||||
};
|
||||
(width > 0 && height > 0).then_some(Thumbnail { width, height, rgba })
|
||||
}
|
||||
|
||||
/// What kind of file `path` is, for its picture and its icon.
|
||||
|
||||
@@ -204,3 +204,32 @@ fn sketch_files_show_their_preview_png() {
|
||||
std::fs::write(&junk, [0xFFu8; 64]).unwrap();
|
||||
assert_eq!(file_preview(&junk, 640), Preview::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thumbnail_decode_keeps_stored_orientation_and_supports_webp_and_gif() {
|
||||
// 24x16 JPEG with EXIF orientation 6 (rotate 90 CW) must keep stored 24x16 / 12x8 dimensions.
|
||||
let rgb = image::RgbImage::from_pixel(24, 16, image::Rgb([200, 40, 20]));
|
||||
let mut jpg = Vec::new();
|
||||
rgb.write_to(&mut Cursor::new(&mut jpg), image::ImageFormat::Jpeg).unwrap();
|
||||
let mut exif = b"Exif\0\0II\x2a\0\x08\0\0\0\x01\0\x12\x01\x03\0\x01\0\0\0".to_vec();
|
||||
exif.extend_from_slice(&6u16.to_le_bytes());
|
||||
exif.extend_from_slice(&[0; 6]);
|
||||
let mut oriented = jpg[..2].to_vec();
|
||||
oriented.extend_from_slice(&[0xff, 0xe1]);
|
||||
oriented.extend_from_slice(&u16::try_from(exif.len() + 2).unwrap().to_be_bytes());
|
||||
oriented.extend_from_slice(&exif);
|
||||
oriented.extend_from_slice(&jpg[2..]);
|
||||
|
||||
let full = decode_thumbnail(&oriented, 64).unwrap();
|
||||
assert_eq!((full.width, full.height), (24, 16));
|
||||
let scaled = decode_thumbnail(&oriented, 12).unwrap();
|
||||
assert_eq!((scaled.width, scaled.height), (12, 8));
|
||||
|
||||
let img = image::RgbaImage::from_pixel(10, 6, image::Rgba([10, 20, 30, 255]));
|
||||
for fmt in [image::ImageFormat::WebP, image::ImageFormat::Gif] {
|
||||
let mut bytes = Vec::new();
|
||||
img.write_to(&mut Cursor::new(&mut bytes), fmt).unwrap();
|
||||
let thumb = decode_thumbnail(&bytes, 64).unwrap();
|
||||
assert_eq!((thumb.width, thumb.height), (10, 6), "{fmt:?}");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user