Merge pull request #2515 from Terra854/fix/u16-thumbnail-precision

Preserve 16-bit precision when scaling thumbnails
This commit is contained in:
FredApps
2026-11-20 08:49:24 +07:00
committed by GitHub
2 changed files with 159 additions and 9 deletions
+85
View File
@@ -237,6 +237,91 @@ fn grey_profiles() {
assert!(near(px[0], [188.0; 3], 2.0) && near(px[1], [255.0; 3], 1.0), "{px:?}");
}
/// A procedural 2 × 2 PNG; confirm the encoder and shared decoder keep every 16-bit sample.
fn png16(samples: &[u16], kind: ExtendedColorType, profile: Option<Vec<u8>>) -> Vec<u8> {
let raw: Vec<u8> = samples.iter().flat_map(|v| v.to_ne_bytes()).collect();
let mut bytes = Vec::new();
encode(image::codecs::png::PngEncoder::new(&mut bytes), &raw, 2, 2, kind, profile);
let decoded = craft_image_codecs::decode(&bytes).unwrap();
assert_eq!(decoded.sample_type(), craft_image_codecs::SampleType::U16);
assert_eq!(decoded.to_u16_samples().unwrap(), samples);
bytes
}
#[test]
fn rgba16_thumbnail_averages_before_quantizing() {
let bytes = png16(&[0, 0, 0, 65535, 256, 256, 256, 65535].repeat(2), ExtendedColorType::Rgba16, None);
let (p, _) = images::decode_within(&bytes, ColorProfile::Srgb, 1, u64::MAX).unwrap();
assert_eq!((p.width(), p.height()), (1, 1));
// Average 128 rounds to U8 zero. Quantizing first gives 0 and 1, whose average rounds to 1.
assert_eq!(p.data(), &[0, 0, 0, 255]);
}
#[test]
fn gray_alpha16_thumbnail_averages_before_quantizing_and_profile_conversion() {
let bytes = png16(&[0, 65535, 256, 65535].repeat(2), ExtendedColorType::La16, Some(icc(b"GRAY", "Linear grey", SRGB_D50, &Trc::Gamma(1.0))));
let source = Source::of(&bytes);
assert_eq!(source.name.as_deref(), Some("Linear grey"));
assert!(source.is_gray());
let (p, fallback) = images::decode_within(&bytes, ColorProfile::Srgb, 1, u64::MAX).unwrap();
assert!(!fallback, "the greyscale ICC profile must be used");
assert_eq!((p.width(), p.height()), (1, 1));
// Resize to grey 128, quantize to zero, then apply the existing 8-bit ICC transform.
assert_eq!(p.data(), &[0, 0, 0, 255]);
}
#[test]
fn gray_alpha16_thumbnail_keeps_alpha_precision_until_after_scaling() {
let bytes = png16(&[65535, 0, 65535, 256].repeat(2), ExtendedColorType::La16, Some(icc(b"GRAY", "Linear grey", SRGB_D50, &Trc::Gamma(1.0))));
assert!(Source::of(&bytes).is_gray());
let (p, fallback) = images::decode_within(&bytes, ColorProfile::Srgb, 1, u64::MAX).unwrap();
assert!(!fallback);
assert_eq!((p.width(), p.height()), (1, 1));
// Alpha averages to 128 and quantizes to zero, so premultiplication clears the white RGB.
assert_eq!(p.data(), &[0, 0, 0, 0]);
}
#[test]
fn u16_thumbnail_matches_previous_box_sampling_at_nonintegral_ratio() {
// For 16→14, the legacy floating-point edge includes source pixel 8 in output pixel 6.
for (w, h, limit) in [(7, 5, 4), (16, 1, 14)] {
let source = image::ImageBuffer::from_fn(w, h, |x, y| image::Rgb([if x == 8 { u16::MAX } else { 0 }, 1500 * y as u16, 4000 * x as u16]));
let raw: Vec<u8> = source.as_raw().iter().flat_map(|sample| sample.to_ne_bytes()).collect();
let mut bytes = Vec::new();
encode(image::codecs::png::PngEncoder::new(&mut bytes), &raw, w, h, ExtendedColorType::Rgb16, None);
let expected = image::DynamicImage::ImageRgb16(source).thumbnail(limit, limit).to_rgba8();
let (p, _) = images::decode_within(&bytes, ColorProfile::Srgb, limit, u64::MAX).unwrap();
assert_eq!((p.width(), p.height()), expected.dimensions());
assert_eq!(p.data(), expected.as_raw(), "{w}×{h} with side limit {limit}");
}
}
#[test]
fn u16_thumbnail_handles_a_source_rectangle_larger_than_a_u32_sum() {
let (w, h) = (257, 257);
let samples = vec![u8::MAX; w as usize * h as usize * 2];
let mut bytes = Vec::new();
encode(image::codecs::png::PngEncoder::new(&mut bytes), &samples, w, h, ExtendedColorType::L16, None);
let (p, _) = images::decode_within(&bytes, ColorProfile::Srgb, 1, 512 << 20).unwrap();
assert_eq!((p.width(), p.height()), (1, 1));
assert_eq!(p.data(), &[255; 4]);
}
#[test]
fn full_size_u16_images_keep_the_existing_quantization() {
let rgba = png16(&[0, 256, 32768, 65535].repeat(4), ExtendedColorType::Rgba16, None);
let p = images::decode(&rgba).unwrap();
assert_eq!((p.width(), p.height()), (2, 2));
assert_eq!(p.data(), &[0, 1, 128, 255].repeat(4));
let grey = png16(&[0, 256].repeat(4), ExtendedColorType::La16, Some(icc(b"GRAY", "Linear grey", SRGB_D50, &Trc::Gamma(1.0))));
let p = images::decode(&grey).unwrap();
assert_eq!((p.width(), p.height()), (2, 2));
assert_eq!(p.data(), &[0, 0, 0, 1].repeat(4));
}
#[test]
fn unusable_profiles_fall_back_to_srgb() {
let img = samples();
+74 -9
View File
@@ -13,6 +13,7 @@
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock};
use craft_image_codecs::{ChannelLayout, SampleType};
use figcraft_color::{ColorProfile, ImageFilters, PaintKind};
use figcraft_doc::{Document, ImageData, NodeId};
use tiny_skia::Pixmap;
@@ -127,9 +128,20 @@ pub(crate) fn decode_within(bytes: &[u8], target: ColorProfile, max_side: u32, m
let img = craft_image_codecs::decode_with(bytes, &opts).ok()?;
let source = crate::image_profile::Source::from_decoded(bytes, img.icc.as_deref());
let is_gray = source.is_gray() && img.layout().is_gray();
let layout = if is_gray { craft_image_codecs::ChannelLayout::GrayA } else { craft_image_codecs::ChannelLayout::Rgba };
let converted = img.converted(layout, craft_image_codecs::SampleType::U8);
let (w, h, pixels) = thumbnail_u8(converted.width(), converted.height(), max_side, is_gray, converted.into_owned().into_data())?;
let layout = if is_gray { ChannelLayout::GrayA } else { ChannelLayout::Rgba };
let original = img.dimensions();
let (w, h) = thumbnail_size(original.0, original.1, max_side)?;
let pixels = if original != (w, h)
&& img.sample_type() == SampleType::U16
&& matches!(img.layout(), ChannelLayout::Gray | ChannelLayout::GrayA | ChannelLayout::Rgb | ChannelLayout::Rgba)
{
let thumbnail = thumbnail_u16(&img, w, h)?;
drop(img);
thumbnail.convert(layout, SampleType::U8).into_data()
} else {
let converted = img.converted(layout, SampleType::U8);
thumbnail_u8(original, (w, h), is_gray, converted.into_owned().into_data())?
};
if is_gray {
let rgba = source.convert_u8(w, h, true, &pixels, target)?;
return Some((premultiplied_rgba(w, h, &rgba)?, false));
@@ -140,27 +152,80 @@ pub(crate) fn decode_within(bytes: &[u8], target: ColorProfile, max_side: u32, m
}
}
/// Scale `pixels` (`GrayA` when `is_gray`, else `Rgba`) down to fit within `max_side` per side,
/// keeping aspect ratio.
fn thumbnail_u8(w: u32, h: u32, max_side: u32, is_gray: bool, pixels: Vec<u8>) -> Option<(u32, u32, Vec<u8>)> {
/// Dimensions of a nonempty, aspect-fit thumbnail within the requested side limit.
fn thumbnail_size(w: u32, h: u32, max_side: u32) -> Option<(u32, u32)> {
if w == 0 || h == 0 {
return None;
}
if w <= max_side && h <= max_side {
return Some((w, h, pixels));
return Some((w, h));
}
let ratio = (f64::from(max_side) / f64::from(w)).min(f64::from(max_side) / f64::from(h));
let nw = (f64::from(w) * ratio).round().max(1.0) as u32;
let nh = (f64::from(h) * ratio).round().max(1.0) as u32;
Some((nw, nh))
}
/// Scale `pixels` in GrayA or RGBA layout.
fn thumbnail_u8((w, h): (u32, u32), (nw, nh): (u32, u32), is_gray: bool, pixels: Vec<u8>) -> Option<Vec<u8>> {
if (w, h) == (nw, nh) {
return Some(pixels);
}
if is_gray {
let buf = image::ImageBuffer::<image::LumaA<u8>, _>::from_raw(w, h, pixels)?;
Some((nw, nh, image::imageops::thumbnail(&buf, nw, nh).into_raw()))
Some(image::imageops::thumbnail(&buf, nw, nh).into_raw())
} else {
let buf = image::RgbaImage::from_raw(w, h, pixels)?;
Some((nw, nh, image::imageops::thumbnail(&buf, nw, nh).into_raw()))
Some(image::imageops::thumbnail(&buf, nw, nh).into_raw())
}
}
/// Average native samples within each thumbnail pixel's source rectangle. Use wide sums
/// because a large reduction can overflow the image crate's U16 thumbnail accumulator.
fn thumbnail_u16(img: &craft_image_codecs::Image, nw: u32, nh: u32) -> Option<craft_image_codecs::Image> {
let (w, h) = img.dimensions();
let layout = img.layout();
let channels = layout.channels();
let pixel_bytes = channels * 2;
let row_bytes = (w as usize).checked_mul(pixel_bytes)?;
let output_bytes = (nw as usize).checked_mul(nh as usize)?.checked_mul(pixel_bytes)?;
let mut data = Vec::new();
data.try_reserve_exact(output_bytes).ok()?;
let rows = img.data().chunks_exact(row_bytes);
let x_ratio = w as f32 / nw as f32;
let y_ratio = h as f32 / nh as f32;
// Keep the old thumbnail's floating-point box boundaries. Every axis scales down, so
// a rounding edge case still needs at least one source sample.
let source_span = |index: u32, input: u32, ratio: f32| {
let offset = index as f32 * ratio;
let start = (offset.ceil() as u32).min(input - 1);
let end = ((offset + ratio).ceil() as u32).clamp(start + 1, input);
start as usize..end as usize
};
for y in 0..nh {
let y_span = source_span(y, h, y_ratio);
let band = rows.clone().skip(y_span.start).take(y_span.len());
for x in 0..nw {
let x_span = source_span(x, w, x_ratio);
let bytes = x_span.start * pixel_bytes..x_span.end * pixel_bytes;
let count = x_span.len() as u64 * y_span.len() as u64;
let mut sums = [0_u64; 4];
for row in band.clone() {
for pixel in row.get(bytes.clone())?.chunks_exact(pixel_bytes) {
for (sum, sample) in sums.iter_mut().zip(pixel.as_chunks::<2>().0) {
*sum += u64::from(u16::from_ne_bytes(*sample));
}
}
}
for sum in sums.iter().take(channels) {
let sample = ((sum + count / 2) / count) as u16;
data.extend_from_slice(&sample.to_ne_bytes());
}
}
}
craft_image_codecs::Image::from_raw(nw, nh, layout, SampleType::U16, data).ok()
}
/// Whether image `hash`, decoded as `pm`, has no transparent pixels (filters and colour profiles
/// keep alpha). Scanned once per image.
pub(crate) fn opaque(hash: &str, pm: &Pixmap) -> bool {