1use std::{io::Cursor, path::Path};
4
5use image_codec::{DynamicImage, ImageBuffer};
6
7use crate::{DType, Error, Image, ImageFormat, ImageLayout, Result};
8
9use super::{ImageCodec, codec_from_path, external_format};
10
11pub fn encode(image: &Image, codec: ImageCodec, quality: u32) -> Result<Vec<u8>> {
22 if codec == ImageCodec::Auto {
23 return Err(Error::invalid_argument(
24 "image::encode requires an explicit codec",
25 ));
26 }
27 let packed = read_packed_pixels(image, codec)?;
28 encode_packed(&packed, codec, quality)
29}
30
31pub fn save_file(path: impl AsRef<Path>, image: &Image, quality: u32) -> Result<()> {
41 let path = path.as_ref();
42 if path.as_os_str().is_empty() {
43 return Err(Error::invalid_argument("image::save_file path is empty"));
44 }
45 let codec = codec_from_path(path).ok_or_else(|| {
46 Error::invalid_argument("image::save_file expected .jpg, .jpeg, .png, .webp, .bmp, or .tga")
47 })?;
48 let encoded = encode(image, codec, quality)?;
49 std::fs::write(path, encoded).map_err(|source| Error::io("image file write", source))
50}
51
52pub fn save_rgba_file(
63 rgba: &[u8],
64 width: u32,
65 height: u32,
66 path: impl AsRef<Path>,
67 quality: u32,
68) -> Result<()> {
69 let path = path.as_ref();
70 if path.as_os_str().is_empty() {
71 return Err(Error::invalid_argument(
72 "image::save_rgba_file path is empty",
73 ));
74 }
75 let codec = codec_from_path(path).ok_or_else(|| {
76 Error::invalid_argument(
77 "image::save_rgba_file expected .jpg, .jpeg, .png, .webp, .bmp, or .tga",
78 )
79 })?;
80 let expected = usize::try_from(width)
81 .ok()
82 .and_then(|value| value.checked_mul(usize::try_from(height).ok()?))
83 .and_then(|value| value.checked_mul(4))
84 .ok_or_else(|| Error::out_of_range("RGBA image byte count overflows usize"))?;
85 if width == 0 || height == 0 || rgba.len() != expected {
86 return Err(Error::invalid_argument(
87 "image::save_rgba_file byte count must equal width * height * 4 for non-zero dimensions",
88 ));
89 }
90 let packed = PackedPixels {
91 data: rgba.to_vec(),
92 width,
93 height,
94 format: ImageFormat::Rgba,
95 };
96 let encoded = encode_packed(&packed, codec, quality)?;
97 std::fs::write(path, encoded).map_err(|source| Error::io("RGBA image file write", source))
98}
99
100struct PackedPixels {
101 data: Vec<u8>,
102 width: u32,
103 height: u32,
104 format: ImageFormat,
105}
106
107fn read_packed_pixels(image: &Image, codec: ImageCodec) -> Result<PackedPixels> {
108 if !matches!(image.layout(), ImageLayout::Nchw | ImageLayout::Chw) {
109 return Err(Error::invalid_argument(
110 "image::encode requires Nchw or Chw layout",
111 ));
112 }
113 if image.batch_size() != 1 {
114 return Err(Error::invalid_argument(
115 "image::encode requires one image; select a batch item explicitly",
116 ));
117 }
118 if image.dtype() != DType::F32 {
119 return Err(Error::invalid_argument(
120 "image::encode requires FP32 image data",
121 ));
122 }
123 let width = u32::try_from(image.width())
124 .map_err(|_| Error::out_of_range("image width exceeds codec limits"))?;
125 let height = u32::try_from(image.height())
126 .map_err(|_| Error::out_of_range("image height exceeds codec limits"))?;
127 if width == 0 || height == 0 {
128 return Err(Error::invalid_argument(
129 "image::encode requires non-zero dimensions",
130 ));
131 }
132 let planar = image.as_matrix().read_f32()?;
133 pack_planar(&planar, width, height, image.format(), codec)
134}
135
136fn pack_planar(
137 planar: &[f32],
138 width: u32,
139 height: u32,
140 input_format: ImageFormat,
141 codec: ImageCodec,
142) -> Result<PackedPixels> {
143 let pixels = usize::try_from(width)
144 .ok()
145 .and_then(|value| value.checked_mul(usize::try_from(height).ok()?))
146 .ok_or_else(|| Error::out_of_range("image pixel count overflows usize"))?;
147 let expected = pixels
148 .checked_mul(input_format.channels())
149 .ok_or_else(|| Error::out_of_range("image element count overflows usize"))?;
150 if planar.len() != expected {
151 return Err(Error::internal(
152 "image storage length does not match its semantic metadata",
153 ));
154 }
155
156 let output_format = match (codec, input_format) {
157 (ImageCodec::Jpeg | ImageCodec::Webp, ImageFormat::GrayAlpha) => ImageFormat::Rgb,
158 (ImageCodec::Webp, ImageFormat::Gray) => ImageFormat::Rgb,
159 (_, ImageFormat::Bgr) => ImageFormat::Rgb,
160 (_, ImageFormat::Bgra) => ImageFormat::Rgba,
161 (_, format) => format,
162 };
163 let output_channels = output_format.channels();
164 let output_len = pixels
165 .checked_mul(output_channels)
166 .ok_or_else(|| Error::out_of_range("packed image byte count overflows usize"))?;
167 let mut data = Vec::new();
168 data
169 .try_reserve_exact(output_len)
170 .map_err(|_| Error::resource_exhausted("packed image allocation failed"))?;
171 data.resize(output_len, 0);
172 let sample = |pixel: usize, channel: usize| quantize(planar[channel * pixels + pixel]);
173 for pixel in 0..pixels {
174 let destination = &mut data[pixel * output_channels..(pixel + 1) * output_channels];
175 match input_format {
176 ImageFormat::Gray => {
177 let gray = sample(pixel, 0);
178 destination.fill(gray);
179 }
180 ImageFormat::GrayAlpha if output_channels == 2 => {
181 destination[0] = sample(pixel, 0);
182 destination[1] = sample(pixel, 1);
183 }
184 ImageFormat::GrayAlpha => {
185 let gray = sample(pixel, 0);
186 destination.fill(gray);
187 }
188 ImageFormat::Rgb | ImageFormat::Rgba => {
189 for (channel, value) in destination.iter_mut().enumerate() {
190 *value = sample(pixel, channel);
191 }
192 }
193 ImageFormat::Bgr | ImageFormat::Bgra => {
194 destination[0] = sample(pixel, 2);
195 destination[1] = sample(pixel, 1);
196 destination[2] = sample(pixel, 0);
197 if output_channels == 4 {
198 destination[3] = sample(pixel, 3);
199 }
200 }
201 }
202 }
203 Ok(PackedPixels {
204 data,
205 width,
206 height,
207 format: output_format,
208 })
209}
210
211fn quantize(value: f32) -> u8 {
212 if !value.is_finite() {
213 return 0;
214 }
215 (value.clamp(0.0, 1.0).mul_add(255.0, 0.5)) as u8
216}
217
218fn encode_packed(pixels: &PackedPixels, codec: ImageCodec, quality: u32) -> Result<Vec<u8>> {
219 if matches!(codec, ImageCodec::Jpeg | ImageCodec::Webp) && !(1..=100).contains(&quality) {
220 return Err(Error::invalid_argument(
221 "image::encode JPEG and WebP quality must be in [1, 100]",
222 ));
223 }
224 if codec == ImageCodec::Webp {
225 let quality = u8::try_from(quality)
226 .map_err(|_| Error::invalid_argument("image::encode quality exceeds u8"))?;
227 let encoder = match pixels.format {
228 ImageFormat::Rgb => webp_codec::Encoder::from_rgb(&pixels.data, pixels.width, pixels.height),
229 ImageFormat::Rgba => {
230 webp_codec::Encoder::from_rgba(&pixels.data, pixels.width, pixels.height)
231 }
232 _ => {
233 return Err(Error::internal(
234 "WebP packed conversion did not produce RGB or RGBA pixels",
235 ));
236 }
237 };
238 let memory = encoder
239 .encode_simple(false, f32::from(quality))
240 .map_err(|source| Error::internal(format!("WebP encode failed: {source:?}")))?;
241 return Ok(memory.to_vec());
242 }
243
244 let dynamic = dynamic_image(pixels)?;
245 let mut encoded = Vec::new();
246 if codec == ImageCodec::Jpeg {
247 let quality = u8::try_from(quality)
248 .map_err(|_| Error::invalid_argument("image::encode quality exceeds u8"))?;
249 let encoder = image_codec::codecs::jpeg::JpegEncoder::new_with_quality(&mut encoded, quality);
250 dynamic
251 .write_with_encoder(encoder)
252 .map_err(|source| Error::backend_failure("image", "JPEG encode", source))?;
253 } else {
254 let format = external_format(codec)
255 .ok_or_else(|| Error::invalid_argument("image::encode requires an explicit codec"))?;
256 dynamic
257 .write_to(&mut Cursor::new(&mut encoded), format)
258 .map_err(|source| Error::backend_failure("image", "encode", source))?;
259 }
260 Ok(encoded)
261}
262
263fn dynamic_image(pixels: &PackedPixels) -> Result<DynamicImage> {
264 macro_rules! buffer {
265 ($pixel:ty, $variant:ident) => {{
266 let image =
267 ImageBuffer::<$pixel, _>::from_raw(pixels.width, pixels.height, pixels.data.clone())
268 .ok_or_else(|| Error::internal("packed image metadata is inconsistent"))?;
269 DynamicImage::$variant(image)
270 }};
271 }
272 Ok(match pixels.format {
273 ImageFormat::Gray => buffer!(image_codec::Luma<u8>, ImageLuma8),
274 ImageFormat::GrayAlpha => buffer!(image_codec::LumaA<u8>, ImageLumaA8),
275 ImageFormat::Rgb => buffer!(image_codec::Rgb<u8>, ImageRgb8),
276 ImageFormat::Rgba => buffer!(image_codec::Rgba<u8>, ImageRgba8),
277 ImageFormat::Bgr | ImageFormat::Bgra => {
278 return Err(Error::internal(
279 "packed image conversion retained a BGR channel order",
280 ));
281 }
282 })
283}