1#![deny(missing_docs)]
11
12#[cfg(doctest)]
14#[doc = include_str!("../README.md")]
15pub struct ReadmeDoctests;
16
17use std::error::Error;
18use std::fmt;
19
20use frus_core::{DecodeSize, ImageData};
21
22#[derive(Debug)]
24pub struct DecodeError(String);
25
26impl DecodeError {
27 pub fn message(&self) -> &str {
29 &self.0
30 }
31}
32
33impl fmt::Display for DecodeError {
34 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35 write!(f, "image decoding failed: {}", self.0)
36 }
37}
38
39impl Error for DecodeError {}
40
41pub fn decode(bytes: &[u8]) -> Result<ImageData, DecodeError> {
56 let decoded = image::load_from_memory(bytes).map_err(|e| DecodeError(e.to_string()))?;
57 let rgba = decoded.to_rgba8();
58 let (width, height) = rgba.dimensions();
59 Ok(ImageData::from_rgba(width, height, rgba.into_raw()))
60}
61
62pub fn dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
75 image::ImageReader::new(std::io::Cursor::new(bytes))
76 .with_guessed_format()
77 .ok()?
78 .into_dimensions()
79 .ok()
80}
81
82pub fn decode_at(bytes: &[u8], size: DecodeSize) -> Result<ImageData, DecodeError> {
103 if size.is_full() {
104 return decode(bytes);
105 }
106 if bytes.starts_with(&[0xFF, 0xD8]) {
107 if let Some(scaled) = scaled_jpeg(bytes, size) {
110 return Ok(scaled);
111 }
112 }
113 let decoded = image::load_from_memory(bytes).map_err(|e| DecodeError(e.to_string()))?;
114 let rgba = decoded.to_rgba8();
115 drop(decoded);
116 let (width, height) = size.target(rgba.width(), rgba.height());
117 let rgba = downsample(rgba, width, height);
118 Ok(ImageData::from_rgba(width, height, rgba.into_raw()))
119}
120
121fn scaled_jpeg(bytes: &[u8], size: DecodeSize) -> Option<ImageData> {
124 let mut decoder = jpeg_decoder::Decoder::new(bytes);
125 decoder.read_info().ok()?;
126 let info = decoder.info()?;
127 let full = (u32::from(info.width), u32::from(info.height));
128 let (width, height) = size.target(full.0, full.1);
129 if (width, height) == full {
130 return None;
131 }
132 decoder.scale(width as u16, height as u16).ok()?;
135 let pixels = decoder.decode().ok()?;
136 let info = decoder.info()?;
137 let (scaled_width, scaled_height) = (u32::from(info.width), u32::from(info.height));
138 let rgba: Vec<u8> = match info.pixel_format {
139 jpeg_decoder::PixelFormat::RGB24 => pixels
140 .as_chunks::<3>()
141 .0
142 .iter()
143 .flat_map(|&[r, g, b]| [r, g, b, 255])
144 .collect(),
145 jpeg_decoder::PixelFormat::L8 => pixels.iter().flat_map(|&l| [l, l, l, 255]).collect(),
146 jpeg_decoder::PixelFormat::L16 | jpeg_decoder::PixelFormat::CMYK32 => return None,
147 };
148 let rgba = image::RgbaImage::from_raw(scaled_width, scaled_height, rgba)?;
149 let rgba = downsample(rgba, width, height);
150 Some(ImageData::from_rgba(width, height, rgba.into_raw()))
151}
152
153fn downsample(rgba: image::RgbaImage, width: u32, height: u32) -> image::RgbaImage {
165 if rgba.dimensions() == (width, height) {
166 return rgba;
167 }
168 let translucent = rgba.pixels().any(|p| p[3] < 255);
169 let mut img = rgba;
170 if translucent {
171 for p in img.pixels_mut() {
172 let a = u16::from(p[3]);
173 for c in 0..3 {
174 p[c] = ((u16::from(p[c]) * a + 127) / 255) as u8;
175 }
176 }
177 }
178 while img.width() / 2 >= width * 2 && img.height() / 2 >= height * 2 {
179 img = halve(&img);
180 }
181 let mut out =
182 image::imageops::resize(&img, width, height, image::imageops::FilterType::Triangle);
183 if translucent {
184 for p in out.pixels_mut() {
185 let a = u16::from(p[3]);
186 for c in 0..3 {
187 if let Some(v) = (u16::from(p[c]) * 255 + a / 2).checked_div(a) {
189 p[c] = v.min(255) as u8;
190 }
191 }
192 }
193 }
194 out
195}
196
197fn halve(img: &image::RgbaImage) -> image::RgbaImage {
200 let (width, height) = (img.width() / 2, img.height() / 2);
201 let stride = img.width() as usize * 4;
202 let src = img.as_raw();
203 let mut out = Vec::with_capacity(width as usize * height as usize * 4);
204 for y in 0..height as usize {
205 let top = &src[2 * y * stride..][..stride];
206 let bottom = &src[(2 * y + 1) * stride..][..stride];
207 for x in 0..width as usize {
208 let i = x * 8;
209 for c in 0..4 {
210 let sum = u16::from(top[i + c])
211 + u16::from(top[i + 4 + c])
212 + u16::from(bottom[i + c])
213 + u16::from(bottom[i + 4 + c]);
214 out.push(((sum + 2) / 4) as u8);
215 }
216 }
217 }
218 image::RgbaImage::from_raw(width, height, out).expect("the size was computed")
219}
220
221#[cfg(test)]
222mod tests {
223 use super::*;
224 use std::io::Cursor;
225
226 fn encode(img: &image::RgbaImage, format: image::ImageFormat) -> Vec<u8> {
228 let mut bytes = Vec::new();
229 image::DynamicImage::ImageRgba8(img.clone())
230 .write_to(&mut Cursor::new(&mut bytes), format)
231 .expect("encoding");
232 bytes
233 }
234
235 fn sample() -> image::RgbaImage {
236 let mut img = image::RgbaImage::from_pixel(4, 3, image::Rgba([0, 0, 0, 255]));
238 img.put_pixel(0, 0, image::Rgba([255, 0, 0, 255]));
239 img.put_pixel(3, 2, image::Rgba([0, 255, 0, 255]));
240 img
241 }
242
243 #[test]
244 fn png_round_trips_pixels_exactly() {
245 let png = encode(&sample(), image::ImageFormat::Png);
246 let data = decode(&png).expect("PNG decoding");
247 assert_eq!((data.width(), data.height()), (4, 3));
248 let rgba = data.rgba();
249 assert_eq!(&rgba[0..4], &[255, 0, 0, 255]);
251 let last = ((2 * 4 + 3) * 4) as usize;
253 assert_eq!(&rgba[last..last + 4], &[0, 255, 0, 255]);
254 }
255
256 #[test]
257 fn jpeg_decodes_with_correct_dimensions() {
258 let jpeg = encode(&sample(), image::ImageFormat::Jpeg);
260 let data = decode(&jpeg).expect("JPEG decoding");
261 assert_eq!((data.width(), data.height()), (4, 3));
262 assert_eq!(data.rgba().len(), 4 * 3 * 4);
263 }
264
265 #[test]
266 fn format_is_detected_from_magic_bytes() {
267 let png = encode(&sample(), image::ImageFormat::Png);
269 assert!(png.starts_with(&[0x89, 0x50, 0x4E, 0x47]), "PNG header");
270 assert!(decode(&png).is_ok());
271 }
272
273 fn card(width: u32, height: u32) -> image::RgbaImage {
276 image::RgbaImage::from_fn(width, height, |x, y| {
277 image::Rgba([(x * 255 / width) as u8, (y * 255 / height) as u8, 128, 255])
278 })
279 }
280
281 #[test]
282 fn a_full_size_decode_at_is_the_plain_decode() {
283 let png = encode(&sample(), image::ImageFormat::Png);
284 let data = decode_at(&png, DecodeSize::FULL).expect("PNG decoding");
285 assert_eq!(data.rgba(), decode(&png).unwrap().rgba());
286 }
287
288 #[test]
289 fn a_png_is_downsampled_to_the_size_asked() {
290 let png = encode(&card(400, 300), image::ImageFormat::Png);
291 let data = decode_at(&png, DecodeSize::new(Some(80), Some(80))).unwrap();
292 assert_eq!((data.width(), data.height()), (107, 80));
294 assert_eq!(data.rgba().len(), 107 * 80 * 4);
295 let red = |x: usize| data.rgba()[(40 * 107 + x) * 4];
297 assert!(
298 red(5) < red(50) && red(50) < red(100),
299 "{} {} {}",
300 red(5),
301 red(50),
302 red(100)
303 );
304 }
305
306 #[test]
307 fn a_jpeg_is_decoded_scaled_to_the_size_asked() {
308 let jpeg = encode(&card(1600, 1200), image::ImageFormat::Jpeg);
309 let data = decode_at(&jpeg, DecodeSize::new(Some(150), None)).unwrap();
310 assert_eq!((data.width(), data.height()), (150, 113));
311 let mid = &data.rgba()[(56 * 150 + 75) * 4..][..4];
313 assert!((i32::from(mid[0]) - 127).abs() < 12, "{mid:?}");
314 assert!((i32::from(mid[1]) - 127).abs() < 12, "{mid:?}");
315 assert_eq!(mid[3], 255);
316 }
317
318 #[test]
319 fn the_scaled_jpeg_path_agrees_with_the_full_one() {
320 let jpeg = encode(&card(800, 600), image::ImageFormat::Jpeg);
321 let size = DecodeSize::new(Some(100), Some(75));
322 let scaled = scaled_jpeg(&jpeg, size).expect("the scaled path takes this JPEG");
323 let full = image::load_from_memory(&jpeg).unwrap().to_rgba8();
324 let reference = downsample(full, 100, 75);
325 let worst = scaled
326 .rgba()
327 .iter()
328 .zip(reference.as_raw())
329 .map(|(a, b)| (i32::from(*a) - i32::from(*b)).abs())
330 .max()
331 .unwrap();
332 assert!(worst <= 16, "the two paths differ by {worst}");
333 }
334
335 #[test]
336 fn a_halving_is_the_mean_of_four() {
337 let img = image::RgbaImage::from_fn(5, 3, |x, y| {
338 image::Rgba([(x * 40) as u8, (y * 100) as u8, 7, 255])
339 });
340 let half = halve(&img);
341 assert_eq!(half.dimensions(), (2, 1));
342 assert_eq!(half.get_pixel(1, 0).0, [100, 50, 7, 255]);
344 }
345
346 #[test]
347 fn a_large_reduction_matches_the_filter_alone() {
348 let img = card(1200, 900);
349 let ours = downsample(img.clone(), 75, 56);
350 let filter = image::imageops::resize(&img, 75, 56, image::imageops::FilterType::Triangle);
351 let worst = ours
352 .as_raw()
353 .iter()
354 .zip(filter.as_raw())
355 .map(|(a, b)| (i32::from(*a) - i32::from(*b)).abs())
356 .max()
357 .unwrap();
358 assert!(worst <= 6, "the halvings moved a pixel by {worst}");
359 }
360
361 #[test]
362 fn nothing_is_decoded_larger_than_the_file() {
363 let png = encode(&sample(), image::ImageFormat::Png);
364 let data = decode_at(&png, DecodeSize::new(Some(400), Some(300))).unwrap();
365 assert_eq!((data.width(), data.height()), (4, 3));
366 }
367
368 #[test]
369 fn transparent_pixels_do_not_darken_a_downsampled_edge() {
370 let img = image::RgbaImage::from_fn(64, 64, |x, _| match x < 32 {
373 true => image::Rgba([255, 255, 255, 255]),
374 false => image::Rgba([0, 0, 0, 0]),
375 });
376 let png = encode(&img, image::ImageFormat::Png);
377 let data = decode_at(&png, DecodeSize::new(Some(8), None)).unwrap();
378 let p = &data.rgba()[(4 * 8 + 3) * 4..][..4];
381 assert!(p[3] > 0 && p[3] < 255, "{p:?}");
382 assert!(p[0] >= 250, "a darkened edge: {p:?}");
383 }
384
385 #[test]
386 fn dimensions_come_from_the_header() {
387 let png = encode(&card(64, 48), image::ImageFormat::Png);
388 assert_eq!(dimensions(&png), Some((64, 48)));
389 let jpeg = encode(&card(64, 48), image::ImageFormat::Jpeg);
390 assert_eq!(dimensions(&jpeg), Some((64, 48)));
391 assert_eq!(dimensions(b"not an image"), None);
392 }
393
394 #[test]
395 fn garbage_bytes_error_cleanly() {
396 let err = decode(b"not an image at all").unwrap_err();
397 assert!(!err.message().is_empty());
398 let size = DecodeSize::new(Some(10), None);
399 assert!(decode_at(b"not an image at all", size).is_err());
400 assert!(decode_at(&[0xFF, 0xD8, 0, 1, 2], size).is_err());
401 }
402}