oxedyne/fe2o3/fe2o3_graphics/src/convert.rs
4.8 KiB, 1 run
created by r1870400018:75658, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | //! Any picture this crate can read, turned into one every consumer takes. |
| 2 | //! |
| 3 | //! Services and programs that take pictures agree on PNG and JPEG and on little else: a vision |
| 4 | //! model, an OCR service, a typesetter and an `<img>` will each refuse a BMP or a TIFF, while a |
| 5 | //! scanner writes nothing else. This is the step that sits between them, so that a tool handed a |
| 6 | //! scan converts it itself rather than asking a person, or a model, to do it. |
| 7 | //! |
| 8 | //! PNG is the default, because it is lossless and a scan of print is what this mostly sees: flat |
| 9 | //! paper and sharp edges, which PNG holds in less than JPEG does at a quality that keeps the edges. |
| 10 | //! Only where the PNG would be large -- a photograph, whose noise PNG cannot compress -- is a JPEG |
| 11 | //! made as well, and the smaller of the two kept. |
| 12 | //! |
| 13 | //! [Written with AI entirely](https://need2know.ai/entirely-ai/code)\ |
| 14 | //! Anthropic Claude |
| 15 | |
| 16 | use crate::{ |
| 17 | bmp, |
| 18 | gif, |
| 19 | heif, |
| 20 | jpeg, |
| 21 | pixmap::Pixmap, |
| 22 | png, |
| 23 | tiff, |
| 24 | }; |
| 25 | |
| 26 | use oxedyne_fe2o3_core::prelude::*; |
| 27 | use oxedyne_fe2o3_stds::media::Media; |
| 28 | |
| 29 | // A PNG up to this size is kept even where a JPEG would be smaller. |
| 30 | pub const PNG_CEILING: usize = 2 * 1024 * 1024; |
| 31 | |
| 32 | // The JPEG quality a large picture is written at: high enough to keep print legible. |
| 33 | pub const JPEG_QUALITY: u8 = 90; |
| 34 | |
| 35 | /// One picture in a form every consumer takes. |
| 36 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 37 | pub struct Common { |
| 38 | pub media: Media, // Png or Jpeg |
| 39 | pub bytes: Vec<u8>, |
| 40 | pub w: usize, |
| 41 | pub h: usize, |
| 42 | } |
| 43 | |
| 44 | impl Common { |
| 45 | |
| 46 | /// The picture as a `data:` URL. |
| 47 | pub fn data_url(&self) -> String { |
| 48 | fmt!("data:{};base64,{}", self.media.mime(), oxedyne_fe2o3_text::base64::encode(&self.bytes)) |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | /// Can this crate decode a picture in this format? |
| 53 | pub fn decodable(m: Media) -> bool { |
| 54 | matches!(m, Media::Png | Media::Jpeg | Media::Gif | Media::Bmp | Media::Ico | Media::Tiff |
| 55 | | Media::Heic) |
| 56 | } |
| 57 | |
| 58 | /// Decodes a picture in any format [`decodable`] names: a TIFF's first page, a GIF's first frame, |
| 59 | /// an icon's largest picture. |
| 60 | pub fn decode(bytes: &[u8]) -> Outcome<Pixmap> { |
| 61 | match Media::sniff(bytes) { |
| 62 | Media::Png => png::decode(bytes), |
| 63 | Media::Jpeg => jpeg::decode(bytes), |
| 64 | Media::Gif => gif::decode(bytes), |
| 65 | Media::Bmp => bmp::decode(bytes), |
| 66 | Media::Ico => bmp::decode_ico(bytes), |
| 67 | Media::Tiff => tiff::decode(bytes), |
| 68 | Media::Heic => heif::decode(bytes), |
| 69 | m => Err(err!( |
| 70 | "A picture in {} format is not one this can decode.", m.label(); |
| 71 | Invalid, Input, Decode, Unimplemented)), |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | /// Decodes every page of a picture: each of a TIFF's, and the one of anything else. |
| 76 | pub fn decode_pages(bytes: &[u8]) -> Outcome<Vec<Pixmap>> { |
| 77 | match Media::sniff(bytes) { |
| 78 | Media::Tiff => tiff::decode_pages(bytes), |
| 79 | _ => Ok(vec![res!(decode(bytes))]), |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | /// Encodes a pixmap as PNG, or as JPEG where that is much the smaller of a large picture. |
| 84 | pub fn encode(pm: &Pixmap) -> Outcome<Common> { |
| 85 | let p = res!(png::encode(pm)); |
| 86 | let (w, h) = (pm.width(), pm.height()); |
| 87 | let opaque = pm.data().chunks_exact(4).all(|c| c[3] == 255); |
| 88 | if p.len() > PNG_CEILING && opaque { |
| 89 | let opts = jpeg::Options { quality: JPEG_QUALITY, ..Default::default() }; |
| 90 | let j = res!(jpeg::encode_with(pm, &opts)); |
| 91 | if j.len() < p.len() { |
| 92 | return Ok(Common { media: Media::Jpeg, bytes: j, w, h }); |
| 93 | } |
| 94 | } |
| 95 | Ok(Common { media: Media::Png, bytes: p, w, h }) |
| 96 | } |
| 97 | |
| 98 | /// The picture as PNG or JPEG, one for each page. A PNG or a JPEG comes back as it was, unread |
| 99 | /// beyond its size. |
| 100 | pub fn to_common(bytes: &[u8]) -> Outcome<Vec<Common>> { |
| 101 | let m = Media::sniff(bytes); |
| 102 | match m { |
| 103 | Media::Png => { |
| 104 | let (w, h) = res!(png::dimensions(bytes)); |
| 105 | return Ok(vec![Common { media: m, bytes: bytes.to_vec(), w, h }]); |
| 106 | } |
| 107 | Media::Jpeg => { |
| 108 | let (w, h) = res!(jpeg::dimensions(bytes)); |
| 109 | return Ok(vec![Common { media: m, bytes: bytes.to_vec(), w, h }]); |
| 110 | } |
| 111 | _ => (), |
| 112 | } |
| 113 | let pages = res!(decode_pages(bytes).map_err(|e| err!(e, |
| 114 | "Converting a {} picture to PNG or JPEG.", m.label(); Decode))); |
| 115 | let mut out = Vec::with_capacity(pages.len()); |
| 116 | for p in &pages { |
| 117 | out.push(res!(encode(p))); |
| 118 | } |
| 119 | Ok(out) |
| 120 | } |
| 121 | |
| 122 | #[cfg(test)] |
| 123 | mod tests { |
| 124 | use super::*; |
| 125 | use crate::colour::Rgba; |
| 126 | |
| 127 | #[test] |
| 128 | fn test_a_bmp_comes_back_as_a_png_of_the_same_pixels_00() -> Outcome<()> { |
| 129 | let mut pm = res!(Pixmap::filled(40, 30, Rgba::new(255, 255, 255, 255))); |
| 130 | for x in 5..35 { |
| 131 | pm.set_pixel(x, 15, Rgba::new(0, 0, 0, 255)); |
| 132 | } |
| 133 | let b = res!(bmp::encode(&pm)); |
| 134 | assert_eq!(Media::sniff(&b), Media::Bmp); |
| 135 | let out = res!(to_common(&b)); |
| 136 | assert_eq!(out.len(), 1); |
| 137 | assert_eq!(out[0].media, Media::Png); |
| 138 | assert_eq!((out[0].w, out[0].h), (40, 30)); |
| 139 | assert_eq!(res!(png::decode(&out[0].bytes)), pm); |
| 140 | assert!(out[0].data_url().starts_with("data:image/png;base64,")); |
| 141 | Ok(()) |
| 142 | } |
| 143 | |
| 144 | #[test] |
| 145 | fn test_a_png_passes_through_untouched_00() -> Outcome<()> { |
| 146 | let pm = res!(Pixmap::filled(3, 2, Rgba::new(1, 2, 3, 255))); |
| 147 | let p = res!(png::encode(&pm)); |
| 148 | let out = res!(to_common(&p)); |
| 149 | assert_eq!(out[0].bytes, p); |
| 150 | Ok(()) |
| 151 | } |
| 152 | } |