1use serde::Deserialize;
8
9#[derive(Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
11pub struct CropRect {
12 pub x: u32,
13 pub y: u32,
14 pub w: u32,
15 pub h: u32,
16 #[serde(default)]
17 pub sw: Option<u32>,
18 #[serde(default)]
19 pub sh: Option<u32>,
20}
21
22pub fn upright_dims(bytes: &[u8]) -> Option<(u32, u32)> {
24 use image::metadata::Orientation::*;
25 use image::ImageDecoder;
26 let mut decoder = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?.into_decoder().ok()?;
27 let (w, h) = decoder.dimensions();
28 Some(match decoder.orientation().ok() {
29 Some(Rotate90 | Rotate270 | Rotate90FlipH | Rotate270FlipH) => (h, w),
30 _ => (w, h),
31 })
32}
33
34pub fn map_crop(crop: CropRect, actual: (u32, u32)) -> (u32, u32, u32, u32) {
37 let (aw, ah) = actual;
38 let (kx, ky) = match (crop.sw, crop.sh) {
39 (Some(sw), Some(sh)) if sw > 0 && sh > 0 && (sw, sh) != actual => (aw as f64 / sw as f64, ah as f64 / sh as f64),
40 _ => (1.0, 1.0),
41 };
42 let scale = |v: u32, k: f64| (v as f64 * k).round() as u32;
43 let mut w = scale(crop.w, kx).clamp(1, aw.max(1));
44 let mut h = scale(crop.h, ky).clamp(1, ah.max(1));
45 if crop.w == crop.h {
46 let side = w.min(h);
47 (w, h) = (side, side);
48 }
49 let x = scale(crop.x, kx).min(aw.saturating_sub(w));
50 let y = scale(crop.y, ky).min(ah.saturating_sub(h));
51 (x, y, w, h)
52}
53
54#[cfg(test)]
55mod tests {
56 use super::*;
57
58 fn rect(x: u32, y: u32, w: u32, h: u32, measured: Option<(u32, u32)>) -> CropRect {
59 CropRect { x, y, w, h, sw: measured.map(|m| m.0), sh: measured.map(|m| m.1) }
60 }
61
62 #[test]
63 fn a_crop_measured_on_a_scaled_preview_lands_on_the_same_part_of_the_original() {
64 assert_eq!(map_crop(rect(512, 0, 512, 512, Some((1024, 768))), (4000, 3000)), (2000, 0, 2000, 2000));
66 }
67
68 #[test]
69 fn a_crop_measured_on_the_image_itself_is_kept_as_drawn() {
70 assert_eq!(map_crop(rect(10, 20, 30, 40, None), (100, 100)), (10, 20, 30, 40));
71 assert_eq!(map_crop(rect(10, 20, 30, 40, Some((100, 100))), (100, 100)), (10, 20, 30, 40));
72 }
73
74 #[test]
75 fn rounding_never_leaves_the_image_or_unsquares_a_square() {
76 let (x, y, w, h) = map_crop(rect(700, 700, 324, 324, Some((1024, 1024))), (1001, 1003));
77 assert_eq!(w, h);
78 assert!(x + w <= 1001 && y + h <= 1003, "{x} {y} {w} {h}");
79 }
80}
81
82pub fn crop_gif(bytes: &[u8], x: u32, y: u32, w: u32, h: u32) -> Option<Vec<u8>> {
87 if w == 0 || h == 0 || w > u16::MAX as u32 || h > u16::MAX as u32 {
88 return None;
89 }
90 let mut opts = gif::DecodeOptions::new();
91 opts.set_color_output(gif::ColorOutput::Indexed);
92 let mut dec = opts.read_info(std::io::Cursor::new(bytes)).ok()?;
93 if x.checked_add(w)? > dec.width() as u32 || y.checked_add(h)? > dec.height() as u32 {
94 return None;
95 }
96 let global = dec.global_palette().map(<[u8]>::to_vec).unwrap_or_default();
97 let repeat = dec.repeat();
98 let mut out = Vec::new();
99 {
100 let mut enc = gif::Encoder::new(&mut out, w as u16, h as u16, &global).ok()?;
101 enc.set_repeat(repeat).ok()?;
102 let mut held: Option<gif::Frame<'static>> = None;
103 while let Some(f) = dec.read_next_frame().ok()? {
104 let (fl, ft, fw) = (f.left as u32, f.top as u32, f.width as u32);
105 let (x0, y0) = (fl.max(x), ft.max(y));
106 let (x1, y1) = ((fl + fw).min(x + w), (ft + f.height as u32).min(y + h));
107 if x0 >= x1 || y0 >= y1 {
108 held.as_mut()?.delay = held.as_ref()?.delay.saturating_add(f.delay);
109 continue;
110 }
111 let nw = (x1 - x0) as usize;
112 let mut buffer = Vec::with_capacity(nw * (y1 - y0) as usize);
113 for row in y0..y1 {
114 let start = ((row - ft) * fw + (x0 - fl)) as usize;
115 buffer.extend_from_slice(f.buffer.get(start..start + nw)?);
116 }
117 let frame = gif::Frame {
118 delay: f.delay,
119 dispose: f.dispose,
120 transparent: f.transparent,
121 needs_user_input: false,
122 left: (x0 - x) as u16,
123 top: (y0 - y) as u16,
124 width: nw as u16,
125 height: (y1 - y0) as u16,
126 interlaced: false,
127 palette: f.palette.clone(),
128 buffer: std::borrow::Cow::Owned(buffer),
129 };
130 if let Some(prev) = held.replace(frame) {
131 enc.write_frame(&prev).ok()?;
132 }
133 }
134 enc.write_frame(&held?).ok()?;
135 }
136 Some(out)
137}
138
139#[cfg(test)]
140mod gif_tests {
141 use super::crop_gif;
142
143 fn decode(bytes: &[u8]) -> Vec<(image::RgbaImage, u32)> {
144 use image::AnimationDecoder;
145 let d = image::codecs::gif::GifDecoder::new(std::io::Cursor::new(bytes)).unwrap();
146 d.into_frames()
147 .map(|f| {
148 let f = f.unwrap();
149 let (n, dd) = f.delay().numer_denom_ms();
150 (f.into_buffer(), n / dd.max(1))
151 })
152 .collect()
153 }
154
155 fn sample() -> Vec<u8> {
157 let mut out = Vec::new();
158 {
159 let palette = [0u8, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255];
160 let mut enc = gif::Encoder::new(&mut out, 6, 4, &palette).unwrap();
161 enc.set_repeat(gif::Repeat::Infinite).unwrap();
162 let full: Vec<u8> = (0..24).map(|i| (i % 3) as u8).collect();
163 let mut f = gif::Frame::from_indexed_pixels(6, 4, full, None);
164 f.delay = 10;
165 enc.write_frame(&f).unwrap();
166 let mut inside = gif::Frame::from_indexed_pixels(2, 2, vec![1u8; 4], None);
167 (inside.left, inside.top, inside.delay) = (2, 1, 20);
168 enc.write_frame(&inside).unwrap();
169 let mut outside = gif::Frame::from_indexed_pixels(1, 4, vec![2u8; 4], None);
170 (outside.left, outside.delay) = (0, 30);
171 enc.write_frame(&outside).unwrap();
172 }
173 out
174 }
175
176 #[test]
177 fn a_gif_crop_matches_cropping_every_composited_frame() {
178 let src = sample();
179 let out = crop_gif(&src, 1, 0, 4, 4).expect("croppable");
180 let (before, after) = (decode(&src), decode(&out));
181 assert_eq!(after.len(), 2, "the frame outside the crop folds into the one before");
182 assert_eq!(after[1].1, 500, "and lends it its delay (20 + 30 cs)");
183 for (i, (img, _)) in after.iter().enumerate() {
184 assert_eq!((img.width(), img.height()), (4, 4));
185 let want = image::imageops::crop_imm(&before[i].0, 1, 0, 4, 4).to_image();
186 assert_eq!(img.as_raw(), want.as_raw(), "frame {i}");
187 }
188 }
189
190 #[test]
191 fn what_cannot_be_cropped_losslessly_says_so() {
192 let src = sample();
193 assert!(crop_gif(&src, 3, 0, 4, 4).is_none(), "outside the canvas");
194 assert!(crop_gif(b"not a gif", 0, 0, 1, 1).is_none());
195 assert!(crop_gif(&src, 0, 0, 0, 0).is_none());
196 }
197}