1use std::{fs, path::Path};
4
5use crate::{Error, Image, ImageFormat, ImageLayout, Matrix, Result, Runtime};
6
7use super::detect_codec;
8
9pub fn decode_file(path: impl AsRef<Path>, format: ImageFormat) -> Result<Image> {
23 let path = path.as_ref();
24 decode_file_on(&Runtime::current()?, path, format)
25}
26pub fn decode_file_on(
36 runtime: &Runtime,
37 path: impl AsRef<Path>,
38 format: ImageFormat,
39) -> Result<Image> {
40 let path = path.as_ref();
41 if path.as_os_str().is_empty() {
42 return Err(Error::invalid_argument("image::decode_file path is empty"));
43 }
44 let encoded = fs::read(path).map_err(|source| Error::io("image file read", source))?;
45 decode_memory_on(runtime, &encoded, format)
46}
47
48pub fn decode_memory(encoded: &[u8], format: ImageFormat) -> Result<Image> {
62 decode_memory_on(&Runtime::current()?, encoded, format)
63}
64
65pub fn decode_memory_on(runtime: &Runtime, encoded: &[u8], format: ImageFormat) -> Result<Image> {
74 if encoded.is_empty() {
75 return Err(Error::invalid_argument(
76 "image::decode_memory input buffer is empty",
77 ));
78 }
79 if !matches!(
80 format,
81 ImageFormat::Gray | ImageFormat::Rgb | ImageFormat::Rgba
82 ) {
83 return Err(Error::invalid_argument(
84 "image::decode_memory output format must be Gray, Rgb, or Rgba",
85 ));
86 }
87 let codec = detect_codec(encoded).ok_or_else(|| {
88 Error::invalid_argument("image::decode_memory bitstream is unsupported or unrecognized")
89 })?;
90 let external = super::external_format(codec)
91 .ok_or_else(|| Error::internal("detected image codec has no decoder format"))?;
92 let decoded = image_codec::load_from_memory_with_format(encoded, external)
93 .map_err(|source| Error::backend_failure("image", "decode", source))?;
94 let width = usize::try_from(decoded.width())
95 .map_err(|_| Error::out_of_range("decoded image width exceeds usize"))?;
96 let height = usize::try_from(decoded.height())
97 .map_err(|_| Error::out_of_range("decoded image height exceeds usize"))?;
98 if width == 0 || height == 0 {
99 return Err(Error::invalid_argument(
100 "image::decode_memory decoded an empty image",
101 ));
102 }
103
104 let packed = match format {
105 ImageFormat::Gray => decoded.to_luma8().into_raw(),
106 ImageFormat::Rgb => decoded.to_rgb8().into_raw(),
107 ImageFormat::Rgba => decoded.to_rgba8().into_raw(),
108 _ => unreachable!("requested output format was validated"),
109 };
110 upload_packed(runtime, &packed, width, height, format)
111}
112
113fn upload_packed(
114 runtime: &Runtime,
115 packed: &[u8],
116 width: usize,
117 height: usize,
118 format: ImageFormat,
119) -> Result<Image> {
120 let channels = format.channels();
121 let pixels = width
122 .checked_mul(height)
123 .ok_or_else(|| Error::out_of_range("decoded image pixel count overflows usize"))?;
124 let elements = pixels
125 .checked_mul(channels)
126 .ok_or_else(|| Error::out_of_range("decoded image element count overflows usize"))?;
127 if packed.len() != elements {
128 return Err(Error::internal(
129 "decoded image pixel count does not match its metadata",
130 ));
131 }
132 let mut planar = Vec::new();
133 planar
134 .try_reserve_exact(elements)
135 .map_err(|_| Error::resource_exhausted("decoded image allocation failed"))?;
136 planar.resize(elements, 0.0_f32);
137 for pixel in 0..pixels {
138 for channel in 0..channels {
139 planar[channel * pixels + pixel] = f32::from(packed[pixel * channels + channel]) / 255.0;
140 }
141 }
142 let matrix = Matrix::new_from_slice_on(runtime, [1, channels, height, width], &planar)?;
143 Image::new(matrix, ImageLayout::Nchw, format)
144}