artifactize_tools/
image.rs1mod file;
4pub(crate) use file::{read, read_output};
5
6use base64::{
7 Engine, alphabet,
8 engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig, general_purpose::STANDARD},
9};
10
11use std::path::Path;
12
13use super::Content;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
17pub enum Mime {
18 #[serde(rename = "image/png")]
19 Png,
20 #[serde(rename = "image/jpeg")]
21 Jpeg,
22 #[serde(rename = "image/webp")]
23 Webp,
24}
25
26impl Mime {
27 pub const fn as_str(self) -> &'static str {
28 match self {
29 Self::Png => "image/png",
30 Self::Jpeg => "image/jpeg",
31 Self::Webp => "image/webp",
32 }
33 }
34}
35
36impl std::str::FromStr for Mime {
37 type Err = &'static str;
38 fn from_str(text: &str) -> Result<Self, Self::Err> {
39 match text {
40 "image/png" => Ok(Self::Png),
41 "image/jpeg" => Ok(Self::Jpeg),
42 "image/webp" => Ok(Self::Webp),
43 _ => Err("Image MIME type must be image/png, image/jpeg or image/webp."),
44 }
45 }
46}
47
48pub const IMAGE_LIMIT: usize = 4 * 1024 * 1024;
50const PNG_SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n";
52const PNG_IHDR_HEADER: &[u8] = b"\0\0\0\rIHDR";
54const PNG_CHUNK_HEADER_BYTES: usize = 8;
56const PNG_LENGTH_BYTES: usize = std::mem::size_of::<u32>();
58const BASE64_INPUT_BYTES: usize = 3;
60const BASE64_OUTPUT_BYTES: usize = 4;
61const PNG_CHUNK_OVERHEAD_BYTES: usize = 12;
63const PNG_ANIMATION_CONTROL: &[u8] = b"acTL";
65const PNG_END: &[u8] = b"IEND";
67const JPEG_START: &[u8] = b"\xff\xd8\xff";
69const JPEG_LS_MARKER: u8 = 0xf7;
71const RIFF_SIGNATURE: &[u8] = b"RIFF";
73const WEBP_FORM: &[u8] = b"WEBP";
74const RIFF_FORM_TYPE: std::ops::Range<usize> = 8..12;
75
76pub fn from_base64(data: &str, mime_type: &str) -> Result<Content, String> {
78 normalize_base64(data, mime_type.parse()?)
79}
80
81pub fn from_output(
83 root: &Path,
84 path: impl AsRef<Path>,
85 mime_type: &str,
86) -> Result<Content, String> {
87 let mime_type = mime_type.parse()?;
88 normalize(&read_output(root, path.as_ref())?, Some(mime_type))
89}
90
91pub(crate) fn normalize_base64(data: &str, mime_type: Mime) -> Result<Content, String> {
92 if data.len() > IMAGE_LIMIT.div_ceil(BASE64_INPUT_BYTES) * BASE64_OUTPUT_BYTES {
93 return Err("Image exceeds the 4 MiB limit.".into());
94 }
95 let decoder = GeneralPurpose::new(
96 &alphabet::STANDARD,
97 GeneralPurposeConfig::new().with_decode_padding_mode(DecodePaddingMode::Indifferent),
98 );
99 let bytes = decoder
100 .decode(data)
101 .map_err(|_| "Image requires valid base64 data.")?;
102 normalize(&bytes, Some(mime_type))
103}
104
105pub fn normalize(bytes: &[u8], declared: Option<Mime>) -> Result<Content, String> {
106 if bytes.is_empty() || bytes.len() > IMAGE_LIMIT {
107 return Err("Image exceeds the 4 MiB limit or contains no data.".into());
108 }
109 let mime_type = mime_type(bytes)
110 .ok_or("Image must be PNG, JPEG or WebP; GIF, BMP and animated PNG are not supported.")?;
111 if declared.is_some_and(|declared| declared != mime_type) {
112 return Err("Image bytes do not match declared MIME type.".into());
113 }
114 Ok(Content::Image {
115 data: STANDARD.encode(bytes),
116 mime_type,
117 })
118}
119
120fn mime_type(bytes: &[u8]) -> Option<Mime> {
121 if bytes.starts_with(JPEG_START) && bytes.get(JPEG_START.len()) != Some(&JPEG_LS_MARKER) {
122 Some(Mime::Jpeg)
123 } else if bytes.starts_with(PNG_SIGNATURE) {
124 let ihdr = PNG_SIGNATURE.len()..PNG_SIGNATURE.len() + PNG_IHDR_HEADER.len();
125 if bytes.get(ihdr) != Some(PNG_IHDR_HEADER) {
126 return None;
127 }
128 let mut offset = PNG_SIGNATURE.len();
130 while offset < bytes.len() {
131 let header = bytes.get(offset..offset + PNG_CHUNK_HEADER_BYTES)?;
132 let (length, kind) = header.split_at(PNG_LENGTH_BYTES);
133 let length = u32::from_be_bytes(length.try_into().ok()?) as usize;
134 let end = offset
135 .checked_add(PNG_CHUNK_OVERHEAD_BYTES)?
136 .checked_add(length)?;
137 if end > bytes.len() || kind == PNG_ANIMATION_CONTROL {
138 return None;
139 }
140 if kind == PNG_END {
141 return Some(Mime::Png);
142 }
143 offset = end;
144 }
145 None
146 } else if bytes.starts_with(RIFF_SIGNATURE) && bytes.get(RIFF_FORM_TYPE) == Some(WEBP_FORM) {
147 Some(Mime::Webp)
148 } else {
149 None
150 }
151}