/src/image/src/codecs/jpeg/encoder.rs
Line | Count | Source |
1 | | #![allow(clippy::too_many_arguments)] |
2 | | use std::io::Write; |
3 | | use std::{error, fmt}; |
4 | | |
5 | | use crate::error::{ |
6 | | EncodingError, ImageError, ImageFormatHint, ImageResult, UnsupportedError, UnsupportedErrorKind, |
7 | | }; |
8 | | use crate::{ColorType, DynamicImage, ExtendedColorType, ImageEncoder, ImageFormat}; |
9 | | |
10 | | use jpeg_encoder::Encoder; |
11 | | |
12 | | /// Represents a unit in which the density of an image is measured |
13 | | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
14 | | pub enum PixelDensityUnit { |
15 | | /// Represents the absence of a unit, the values indicate only a |
16 | | /// [pixel aspect ratio](https://en.wikipedia.org/wiki/Pixel_aspect_ratio) |
17 | | PixelAspectRatio, |
18 | | |
19 | | /// Pixels per inch (2.54 cm) |
20 | | Inches, |
21 | | |
22 | | /// Pixels per centimeter |
23 | | Centimeters, |
24 | | } |
25 | | |
26 | | /// Controls the resolution of the color information. |
27 | | /// |
28 | | /// Human eye is much less sensitive to the detail of color than brightness. |
29 | | /// JPEG can exploit this to significantly reduce the file size by storing color information |
30 | | /// (Cb and Cr channels) in a lower resolution than brightness (Y channel) without visual quality loss. |
31 | | /// |
32 | | /// See the documentation on each variant for details. |
33 | | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
34 | | #[non_exhaustive] |
35 | | pub enum ChromaSubsampling { |
36 | | /// **4:4:4** Color information is encoded in full resolution. Results in larger file size. |
37 | | /// |
38 | | /// Recommended when the image has small brightly colored elements, e.g. artwork or screenshots. |
39 | | S444, |
40 | | /// **4:2:2** The resolution of color information is reduced by a factor of 2 in the horizontal direction. |
41 | | S422, |
42 | | /// **4:2:0** The resolution of color information is reduced by a factor of 2 both horizontally and vertically. |
43 | | /// |
44 | | /// Results in a smaller file size. Well suited for photographs where it incurs no visial quality loss. |
45 | | S420, |
46 | | } |
47 | | |
48 | | impl ChromaSubsampling { |
49 | 0 | fn to_encoder_repr(self) -> jpeg_encoder::SamplingFactor { |
50 | 0 | match self { |
51 | 0 | ChromaSubsampling::S444 => jpeg_encoder::SamplingFactor::R_4_4_4, |
52 | 0 | ChromaSubsampling::S422 => jpeg_encoder::SamplingFactor::R_4_2_2, |
53 | 0 | ChromaSubsampling::S420 => jpeg_encoder::SamplingFactor::R_4_2_0, |
54 | | } |
55 | 0 | } |
56 | | } |
57 | | |
58 | | /// Represents the pixel density of an image |
59 | | /// |
60 | | /// For example, a 300 DPI image is represented by: |
61 | | /// |
62 | | /// ```rust |
63 | | /// use image::codecs::jpeg::*; |
64 | | /// let hdpi = PixelDensity::dpi(300); |
65 | | /// assert_eq!(hdpi, PixelDensity {density: (300,300), unit: PixelDensityUnit::Inches}) |
66 | | /// ``` |
67 | | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
68 | | pub struct PixelDensity { |
69 | | /// A couple of values for (Xdensity, Ydensity) |
70 | | pub density: (u16, u16), |
71 | | /// The unit in which the density is measured |
72 | | pub unit: PixelDensityUnit, |
73 | | } |
74 | | |
75 | | impl PixelDensity { |
76 | | /// Creates the most common pixel density type: |
77 | | /// the horizontal and the vertical density are equal, |
78 | | /// and measured in pixels per inch. |
79 | | #[must_use] |
80 | 0 | pub fn dpi(density: u16) -> Self { |
81 | 0 | PixelDensity { |
82 | 0 | density: (density, density), |
83 | 0 | unit: PixelDensityUnit::Inches, |
84 | 0 | } |
85 | 0 | } |
86 | | |
87 | | /// Converts pixel density to the representation used by jpeg-encoder crate |
88 | 0 | fn to_encoder_repr(self) -> jpeg_encoder::PixelDensity { |
89 | 0 | let unit = match self.unit { |
90 | 0 | PixelDensityUnit::PixelAspectRatio => jpeg_encoder::PixelDensityUnit::PixelAspectRatio, |
91 | 0 | PixelDensityUnit::Inches => jpeg_encoder::PixelDensityUnit::Inches, |
92 | 0 | PixelDensityUnit::Centimeters => jpeg_encoder::PixelDensityUnit::Centimeters, |
93 | | }; |
94 | 0 | jpeg_encoder::PixelDensity { |
95 | 0 | density: self.density, |
96 | 0 | unit, |
97 | 0 | } |
98 | 0 | } |
99 | | } |
100 | | |
101 | | impl Default for PixelDensity { |
102 | | /// Returns a pixel density with a pixel aspect ratio of 1 |
103 | 0 | fn default() -> Self { |
104 | 0 | PixelDensity { |
105 | 0 | density: (1, 1), |
106 | 0 | unit: PixelDensityUnit::PixelAspectRatio, |
107 | 0 | } |
108 | 0 | } |
109 | | } |
110 | | |
111 | | /// Errors that can occur when encoding a JPEG image |
112 | | #[derive(Debug, Copy, Clone)] |
113 | | enum EncoderError { |
114 | | /// JPEG does not support this size |
115 | | InvalidSize(u32, u32), |
116 | | } |
117 | | |
118 | | impl fmt::Display for EncoderError { |
119 | 0 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
120 | 0 | match self { |
121 | 0 | EncoderError::InvalidSize(w, h) => f.write_fmt(format_args!( |
122 | 0 | "Invalid image size ({w} x {h}) to encode as JPEG: \ |
123 | 0 | width and height must be >= 1 and <= 65535" |
124 | | )), |
125 | | } |
126 | 0 | } |
127 | | } |
128 | | |
129 | | impl From<EncoderError> for ImageError { |
130 | 0 | fn from(e: EncoderError) -> ImageError { |
131 | 0 | ImageError::Encoding(EncodingError::new(ImageFormat::Jpeg.into(), e)) |
132 | 0 | } |
133 | | } |
134 | | |
135 | | impl error::Error for EncoderError {} |
136 | | |
137 | | /// The representation of a JPEG encoder |
138 | | pub struct JpegEncoder<W: Write> { |
139 | | encoder: Encoder<W>, |
140 | | } |
141 | | |
142 | | impl<W: Write> JpegEncoder<W> { |
143 | | /// Create a new encoder that writes its output to ```w``` |
144 | 0 | pub fn new(w: W) -> JpegEncoder<W> { |
145 | 0 | JpegEncoder::new_with_quality(w, 75) |
146 | 0 | } Unexecuted instantiation: <image::codecs::jpeg::encoder::JpegEncoder<_>>::new Unexecuted instantiation: <image::codecs::jpeg::encoder::JpegEncoder<&mut std::io::cursor::Cursor<alloc::vec::Vec<u8>>>>::new |
147 | | |
148 | | /// Create a new encoder that writes its output to ```w```, and has |
149 | | /// the quality parameter ```quality``` with a value in the range 1-100 |
150 | | /// where 1 is the worst and 100 is the best. |
151 | | /// |
152 | | /// By default quality settings 90 or above use [chroma subsampling](ChromaSubsampling) |
153 | | /// mode [4:4:4](ChromaSubsampling::S444), while quality below 90 subsampling mode |
154 | | /// [4:2:0](ChromaSubsampling::S420). |
155 | | /// This can be overridden using [Self::set_chroma_subsampling]. |
156 | 0 | pub fn new_with_quality(w: W, quality: u8) -> JpegEncoder<W> { |
157 | 0 | JpegEncoder { |
158 | 0 | encoder: Encoder::new(w, quality), |
159 | 0 | } |
160 | 0 | } Unexecuted instantiation: <image::codecs::jpeg::encoder::JpegEncoder<_>>::new_with_quality Unexecuted instantiation: <image::codecs::jpeg::encoder::JpegEncoder<&mut std::io::cursor::Cursor<alloc::vec::Vec<u8>>>>::new_with_quality |
161 | | |
162 | | /// Sets the chroma subsampling mode. See [ChromaSubsampling] for details. |
163 | 0 | pub fn set_chroma_subsampling(&mut self, sampling: ChromaSubsampling) { |
164 | 0 | self.encoder.set_sampling_factor(sampling.to_encoder_repr()); |
165 | 0 | } |
166 | | |
167 | | /// Spend extra time optimizing Huffman tables. Slightly reduces file size at the cost of encoding speed. |
168 | | /// |
169 | | /// Defaults to **false**. |
170 | 0 | pub fn set_optimize_huffman_tables(&mut self, optimize: bool) { |
171 | 0 | self.encoder.set_optimized_huffman_tables(optimize); |
172 | 0 | } |
173 | | |
174 | | /// Progressive files allow showing a low-resolution view of the entire image before it's fully downloaded. |
175 | | /// Useful for large images that will be displayed on the web. |
176 | | /// |
177 | | /// Defaults to **false**. |
178 | 0 | pub fn set_progressive(&mut self, progressive: bool) { |
179 | 0 | self.encoder.set_progressive(progressive); |
180 | 0 | } |
181 | | |
182 | | /// Set the pixel density of the images the encoder will encode. |
183 | | /// If this method is not called, then a default pixel aspect ratio of 1x1 will be applied, |
184 | | /// and no DPI information will be stored in the image. |
185 | 0 | pub fn set_pixel_density(&mut self, pixel_density: PixelDensity) { |
186 | 0 | self.encoder.set_density(pixel_density.to_encoder_repr()); |
187 | 0 | } |
188 | | |
189 | | /// Encodes the image stored in the raw byte buffer ```image``` |
190 | | /// that has dimensions ```width``` and ```height``` |
191 | | /// and ```ColorType``` ```c``` |
192 | | /// |
193 | | /// # Panics |
194 | | /// |
195 | | /// Panics if the buffer does not hold exactly the number of bytes required for the given |
196 | | /// `width`, `height`, and `color_type`, accounting for rows padded to whole bytes for |
197 | | /// sub-byte color types: `height * ((width * color_type.bits_per_pixel() as u32 + 7) / 8)`. |
198 | | #[track_caller] |
199 | 0 | fn encode( |
200 | 0 | self, |
201 | 0 | image: &[u8], |
202 | 0 | width: u32, |
203 | 0 | height: u32, |
204 | 0 | color_type: ExtendedColorType, |
205 | 0 | ) -> ImageResult<()> { |
206 | 0 | let expected_buffer_len = color_type.buffer_size(width, height); |
207 | 0 | assert_eq!( |
208 | | expected_buffer_len, |
209 | 0 | image.len() as u64, |
210 | 0 | "Invalid buffer length: expected {expected_buffer_len} got {} for {width}x{height} image", |
211 | 0 | image.len(), |
212 | | ); |
213 | | |
214 | 0 | let (width, height) = match (u16::try_from(width), u16::try_from(height)) { |
215 | 0 | (Ok(w @ 1..), Ok(h @ 1..)) => (w, h), |
216 | 0 | _ => return Err(EncoderError::InvalidSize(width, height).into()), |
217 | | }; |
218 | | |
219 | 0 | let encode_jpeg = |color: jpeg_encoder::ColorType| { |
220 | 0 | self.encoder |
221 | 0 | .encode(image, width, height, color) |
222 | 0 | .map_err(|err| { |
223 | 0 | ImageError::Encoding(EncodingError::new( |
224 | 0 | ImageFormatHint::Exact(ImageFormat::Jpeg), |
225 | 0 | err, |
226 | 0 | )) |
227 | 0 | }) Unexecuted instantiation: <image::codecs::jpeg::encoder::JpegEncoder<_>>::encode::{closure#0}::{closure#0}Unexecuted instantiation: <image::codecs::jpeg::encoder::JpegEncoder<&mut std::io::cursor::Cursor<alloc::vec::Vec<u8>>>>::encode::{closure#0}::{closure#0} |
228 | 0 | }; Unexecuted instantiation: <image::codecs::jpeg::encoder::JpegEncoder<_>>::encode::{closure#0}Unexecuted instantiation: <image::codecs::jpeg::encoder::JpegEncoder<&mut std::io::cursor::Cursor<alloc::vec::Vec<u8>>>>::encode::{closure#0} |
229 | | |
230 | 0 | match color_type { |
231 | | ExtendedColorType::L8 => { |
232 | 0 | let color = jpeg_encoder::ColorType::Luma; |
233 | 0 | encode_jpeg(color) |
234 | | } |
235 | | ExtendedColorType::Rgb8 => { |
236 | 0 | let color = jpeg_encoder::ColorType::Rgb; |
237 | 0 | encode_jpeg(color) |
238 | | } |
239 | 0 | _ => Err(ImageError::Unsupported( |
240 | 0 | UnsupportedError::from_format_and_kind( |
241 | 0 | ImageFormat::Jpeg.into(), |
242 | 0 | UnsupportedErrorKind::Color(color_type), |
243 | 0 | ), |
244 | 0 | )), |
245 | | } |
246 | 0 | } Unexecuted instantiation: <image::codecs::jpeg::encoder::JpegEncoder<_>>::encode Unexecuted instantiation: <image::codecs::jpeg::encoder::JpegEncoder<&mut std::io::cursor::Cursor<alloc::vec::Vec<u8>>>>::encode |
247 | | } |
248 | | |
249 | | impl<W: Write> ImageEncoder for JpegEncoder<W> { |
250 | | #[track_caller] |
251 | 0 | fn write_image( |
252 | 0 | self, |
253 | 0 | buf: &[u8], |
254 | 0 | width: u32, |
255 | 0 | height: u32, |
256 | 0 | color_type: ExtendedColorType, |
257 | 0 | ) -> ImageResult<()> { |
258 | 0 | self.encode(buf, width, height, color_type) |
259 | 0 | } Unexecuted instantiation: <image::codecs::jpeg::encoder::JpegEncoder<_> as image::io::encoder::ImageEncoder>::write_image Unexecuted instantiation: <image::codecs::jpeg::encoder::JpegEncoder<&mut std::io::cursor::Cursor<alloc::vec::Vec<u8>>> as image::io::encoder::ImageEncoder>::write_image |
260 | | |
261 | 0 | fn set_icc_profile(&mut self, icc_profile: Vec<u8>) -> Result<(), UnsupportedError> { |
262 | 0 | self.encoder.add_icc_profile(&icc_profile).map_err(|_| { |
263 | 0 | UnsupportedError::from_format_and_kind( |
264 | 0 | ImageFormat::Jpeg.into(), |
265 | 0 | UnsupportedErrorKind::GenericFeature("ICC chunk too large".to_string()), |
266 | | ) |
267 | 0 | }) Unexecuted instantiation: <image::codecs::jpeg::encoder::JpegEncoder<_> as image::io::encoder::ImageEncoder>::set_icc_profile::{closure#0}Unexecuted instantiation: <image::codecs::jpeg::encoder::JpegEncoder<&mut std::io::cursor::Cursor<alloc::vec::Vec<u8>>> as image::io::encoder::ImageEncoder>::set_icc_profile::{closure#0} |
268 | 0 | } Unexecuted instantiation: <image::codecs::jpeg::encoder::JpegEncoder<_> as image::io::encoder::ImageEncoder>::set_icc_profile Unexecuted instantiation: <image::codecs::jpeg::encoder::JpegEncoder<&mut std::io::cursor::Cursor<alloc::vec::Vec<u8>>> as image::io::encoder::ImageEncoder>::set_icc_profile |
269 | | |
270 | 0 | fn set_exif_metadata(&mut self, exif: Vec<u8>) -> Result<(), UnsupportedError> { |
271 | 0 | self.encoder.add_exif_metadata(&exif).map_err(|_| { |
272 | 0 | UnsupportedError::from_format_and_kind( |
273 | 0 | ImageFormat::Jpeg.into(), |
274 | 0 | UnsupportedErrorKind::GenericFeature("Exif chunk too large".to_string()), |
275 | | ) |
276 | 0 | })?; Unexecuted instantiation: <image::codecs::jpeg::encoder::JpegEncoder<_> as image::io::encoder::ImageEncoder>::set_exif_metadata::{closure#0}Unexecuted instantiation: <image::codecs::jpeg::encoder::JpegEncoder<&mut std::io::cursor::Cursor<alloc::vec::Vec<u8>>> as image::io::encoder::ImageEncoder>::set_exif_metadata::{closure#0} |
277 | 0 | Ok(()) |
278 | 0 | } Unexecuted instantiation: <image::codecs::jpeg::encoder::JpegEncoder<_> as image::io::encoder::ImageEncoder>::set_exif_metadata Unexecuted instantiation: <image::codecs::jpeg::encoder::JpegEncoder<&mut std::io::cursor::Cursor<alloc::vec::Vec<u8>>> as image::io::encoder::ImageEncoder>::set_exif_metadata |
279 | | |
280 | 0 | fn set_xmp_metadata(&mut self, mut xmp: Vec<u8>) -> Result<(), UnsupportedError> { |
281 | | // XMP is stored in an APP1 segment with namespace prefix "http://ns.adobe.com/xap/1.0/\0" |
282 | | const XMP_NAMESPACE_PREFIX: &[u8] = b"http://ns.adobe.com/xap/1.0/\0"; |
283 | | |
284 | 0 | xmp.extend_from_slice(XMP_NAMESPACE_PREFIX); |
285 | 0 | xmp.rotate_right(XMP_NAMESPACE_PREFIX.len()); |
286 | | |
287 | 0 | self.encoder.add_app_segment(1, xmp).map_err(|_| { |
288 | 0 | UnsupportedError::from_format_and_kind( |
289 | 0 | ImageFormat::Jpeg.into(), |
290 | 0 | UnsupportedErrorKind::GenericFeature("XMP metadata too large".to_string()), |
291 | | ) |
292 | 0 | })?; Unexecuted instantiation: <image::codecs::jpeg::encoder::JpegEncoder<_> as image::io::encoder::ImageEncoder>::set_xmp_metadata::{closure#0}Unexecuted instantiation: <image::codecs::jpeg::encoder::JpegEncoder<&mut std::io::cursor::Cursor<alloc::vec::Vec<u8>>> as image::io::encoder::ImageEncoder>::set_xmp_metadata::{closure#0} |
293 | 0 | Ok(()) |
294 | 0 | } Unexecuted instantiation: <image::codecs::jpeg::encoder::JpegEncoder<_> as image::io::encoder::ImageEncoder>::set_xmp_metadata Unexecuted instantiation: <image::codecs::jpeg::encoder::JpegEncoder<&mut std::io::cursor::Cursor<alloc::vec::Vec<u8>>> as image::io::encoder::ImageEncoder>::set_xmp_metadata |
295 | | |
296 | 0 | fn make_compatible_img( |
297 | 0 | &self, |
298 | 0 | _: crate::io::encoder::MethodSealedToImage, |
299 | 0 | img: &DynamicImage, |
300 | 0 | ) -> Option<DynamicImage> { |
301 | | use ColorType::*; |
302 | 0 | match img.color() { |
303 | 0 | L8 | Rgb8 => None, |
304 | 0 | La8 | L16 | L32F | La16 | La32F => Some(img.to_luma8().into()), |
305 | 0 | Rgba8 | Rgb16 | Rgb32F | Rgba16 | Rgba32F => Some(img.to_rgb8().into()), |
306 | | } |
307 | 0 | } Unexecuted instantiation: <image::codecs::jpeg::encoder::JpegEncoder<_> as image::io::encoder::ImageEncoder>::make_compatible_img Unexecuted instantiation: <image::codecs::jpeg::encoder::JpegEncoder<&mut std::io::cursor::Cursor<alloc::vec::Vec<u8>>> as image::io::encoder::ImageEncoder>::make_compatible_img |
308 | | } |
309 | | |
310 | | #[cfg(test)] |
311 | | mod tests { |
312 | | use std::io::Cursor; |
313 | | |
314 | | #[cfg(feature = "benchmarks")] |
315 | | extern crate test; |
316 | | #[cfg(feature = "benchmarks")] |
317 | | use test::Bencher; |
318 | | |
319 | | use crate::{ColorType, DynamicImage, ExtendedColorType, ImageEncoder, ImageError}; |
320 | | use crate::{ImageDecoder as _, ImageFormat}; |
321 | | |
322 | | use super::super::{JpegDecoder, JpegEncoder}; |
323 | | |
324 | | fn decode(encoded: &[u8]) -> Vec<u8> { |
325 | | let mut decoder = JpegDecoder::new(Cursor::new(encoded)); |
326 | | let layout = decoder.prepare_image().unwrap(); |
327 | | let mut decoded = vec![0; layout.total_bytes() as usize]; |
328 | | decoder |
329 | | .read_image(&mut decoded) |
330 | | .expect("Could not decode image"); |
331 | | decoded |
332 | | } |
333 | | |
334 | | #[test] |
335 | | fn roundtrip_sanity_check() { |
336 | | // create a 1x1 8-bit image buffer containing a single red pixel |
337 | | let img = [255u8, 0, 0]; |
338 | | |
339 | | // encode it into a memory buffer |
340 | | let mut encoded_img = Vec::new(); |
341 | | { |
342 | | let encoder = JpegEncoder::new_with_quality(&mut encoded_img, 100); |
343 | | encoder |
344 | | .write_image(&img, 1, 1, ExtendedColorType::Rgb8) |
345 | | .expect("Could not encode image"); |
346 | | } |
347 | | |
348 | | // decode it from the memory buffer |
349 | | { |
350 | | let decoded = decode(&encoded_img); |
351 | | // note that, even with the encode quality set to 100, we do not get the same image |
352 | | // back. Therefore, we're going to assert that it's at least red-ish: |
353 | | assert_eq!(3, decoded.len()); |
354 | | assert!(decoded[0] > 0x80); |
355 | | assert!(decoded[1] < 0x80); |
356 | | assert!(decoded[2] < 0x80); |
357 | | } |
358 | | } |
359 | | |
360 | | #[test] |
361 | | fn grayscale_roundtrip_sanity_check() { |
362 | | // create a 2x2 8-bit image buffer containing a white diagonal |
363 | | let img = [255u8, 0, 0, 255]; |
364 | | |
365 | | // encode it into a memory buffer |
366 | | let mut encoded_img = Vec::new(); |
367 | | { |
368 | | let encoder = JpegEncoder::new_with_quality(&mut encoded_img, 100); |
369 | | encoder |
370 | | .write_image(&img[..], 2, 2, ExtendedColorType::L8) |
371 | | .expect("Could not encode image"); |
372 | | } |
373 | | |
374 | | // decode it from the memory buffer |
375 | | { |
376 | | let decoded = decode(&encoded_img); |
377 | | // note that, even with the encode quality set to 100, we do not get the same image |
378 | | // back. Therefore, we're going to assert that the diagonal is at least white-ish: |
379 | | assert_eq!(4, decoded.len()); |
380 | | assert!(decoded[0] > 0x80); |
381 | | assert!(decoded[1] < 0x80); |
382 | | assert!(decoded[2] < 0x80); |
383 | | assert!(decoded[3] > 0x80); |
384 | | } |
385 | | } |
386 | | |
387 | | #[test] |
388 | | fn roundtrip_exif_icc() { |
389 | | // create a 2x2 8-bit image buffer containing a white diagonal |
390 | | let img = [255u8, 0, 0, 255]; |
391 | | |
392 | | let exif = vec![1, 2, 3]; |
393 | | let icc = vec![4, 5, 6]; |
394 | | |
395 | | // encode it into a memory buffer |
396 | | let mut encoded_img = Vec::new(); |
397 | | { |
398 | | let mut encoder = JpegEncoder::new_with_quality(&mut encoded_img, 100); |
399 | | |
400 | | encoder.set_exif_metadata(exif.clone()).unwrap(); |
401 | | encoder.set_icc_profile(icc.clone()).unwrap(); |
402 | | |
403 | | encoder |
404 | | .write_image(&img[..], 2, 2, ExtendedColorType::L8) |
405 | | .expect("Could not encode image"); |
406 | | } |
407 | | |
408 | | let mut decoder = JpegDecoder::new(Cursor::new(encoded_img)); |
409 | | let decoded_exif = decoder |
410 | | .exif_metadata() |
411 | | .expect("Error decoding Exif") |
412 | | .expect("Exif is empty"); |
413 | | assert_eq!(exif, decoded_exif); |
414 | | let decoded_icc = decoder |
415 | | .icc_profile() |
416 | | .expect("Error decoding ICC") |
417 | | .expect("ICC is empty"); |
418 | | assert_eq!(icc, decoded_icc); |
419 | | } |
420 | | |
421 | | #[test] |
422 | | fn roundtrip_xmp() { |
423 | | let img = [255u8, 0, 0, 255]; |
424 | | |
425 | | let xmp = b"<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF></rdf:RDF></x:xmpmeta>".to_vec(); |
426 | | |
427 | | let mut encoded_img = Vec::new(); |
428 | | { |
429 | | let mut encoder = JpegEncoder::new_with_quality(&mut encoded_img, 100); |
430 | | encoder.set_xmp_metadata(xmp.clone()).unwrap(); |
431 | | encoder |
432 | | .write_image(&img[..], 2, 2, ExtendedColorType::L8) |
433 | | .expect("Could not encode image"); |
434 | | } |
435 | | |
436 | | let mut decoder = JpegDecoder::new(Cursor::new(encoded_img)); |
437 | | let decoded_xmp = decoder |
438 | | .xmp_metadata() |
439 | | .expect("Error decoding XMP") |
440 | | .expect("XMP is empty"); |
441 | | assert_eq!(xmp, decoded_xmp); |
442 | | } |
443 | | |
444 | | #[test] |
445 | | fn test_image_too_large() { |
446 | | // JPEG cannot encode images larger than 65,535×65,535 |
447 | | // create a 65,536×1 8-bit black image buffer |
448 | | let img = [0; 65_536]; |
449 | | // Try to encode an image that is too large |
450 | | let mut encoded = Vec::new(); |
451 | | let encoder = JpegEncoder::new_with_quality(&mut encoded, 100); |
452 | | let result = encoder.write_image(&img, 65_536, 1, ExtendedColorType::L8); |
453 | | match result { |
454 | | Err(ImageError::Encoding(_)) => (), |
455 | | other => { |
456 | | panic!( |
457 | | "Encoding an image that is too large should return an EncodingError \ |
458 | | it returned {other:?} instead" |
459 | | ) |
460 | | } |
461 | | } |
462 | | } |
463 | | |
464 | | #[test] |
465 | | fn check_color_types() { |
466 | | const ALL: &[ColorType] = &[ |
467 | | ColorType::L8, |
468 | | ColorType::L16, |
469 | | ColorType::La8, |
470 | | ColorType::Rgb8, |
471 | | ColorType::Rgba8, |
472 | | ColorType::La16, |
473 | | ColorType::Rgb16, |
474 | | ColorType::Rgba16, |
475 | | ColorType::Rgb32F, |
476 | | ColorType::Rgba32F, |
477 | | ]; |
478 | | |
479 | | for color in ALL { |
480 | | let image = DynamicImage::new(1, 1, *color); |
481 | | |
482 | | image |
483 | | .write_to(&mut Cursor::new(vec![]), ImageFormat::Jpeg) |
484 | | .expect("supported or converted"); |
485 | | } |
486 | | } |
487 | | |
488 | | #[cfg(feature = "benchmarks")] |
489 | | #[bench] |
490 | | fn bench_jpeg_encoder_new(b: &mut Bencher) { |
491 | | b.iter(|| { |
492 | | let mut y = vec![]; |
493 | | let _x = JpegEncoder::new(&mut y); |
494 | | }); |
495 | | } |
496 | | } |