1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
use crate::{
error::{Error::InvalidExtension, Result},
FrameIterator, Image, Pixel,
};
use std::{
ffi::OsStr,
fmt,
fmt::Display,
io::{Read, Write},
path::Path,
};
#[cfg(feature = "gif")]
use crate::encodings::gif;
#[cfg(feature = "jpeg")]
use crate::encodings::jpeg;
#[cfg(feature = "png")]
use crate::encodings::png;
#[cfg(feature = "webp")]
use crate::encodings::webp;
#[cfg(any(feature = "png", feature = "gif", feature = "jpeg", feature = "webp"))]
use crate::{Decoder, Encoder};
/// Represents the underlying encoding format of an image.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ImageFormat {
/// No known encoding is known for the image.
///
/// This is usually because the image was created manually. See [`Image::set_format`]
/// to manually set the encoding format.
Unknown,
/// The image is encoded in the PNG format.
Png,
/// The image is encoded in the JPEG format.
Jpeg,
/// The image is encoded in the GIF format.
Gif,
/// The image is encoded in the BMP format.
Bmp,
/// The image is encoded in the TIFF format.
Tiff,
/// The image is encoded in the WebP format.
WebP,
}
impl Default for ImageFormat {
fn default() -> Self {
Self::Unknown
}
}
impl ImageFormat {
/// Returns whether the extension is unknown.
#[inline]
#[must_use]
pub fn is_unknown(&self) -> bool {
self == &Self::Unknown
}
/// Parses the given extension and returns the corresponding image format.
///
/// If the extension is an unknown extension, Ok([`ImageFormat::Unknown`]) is returned.
///
/// If the extension is completely invalid and fails to be converted into a `&str`,
/// the [`InvalidExtension`] error is returned.
///
/// # Errors
/// * The extension is completely invalid and failed to be converted into a `&str`.
pub fn from_extension(ext: impl AsRef<OsStr>) -> Result<Self> {
let extension = ext.as_ref().to_str();
Ok(
match extension
.ok_or_else(|| InvalidExtension(ext.as_ref().to_os_string()))?
.to_ascii_lowercase()
.as_str()
{
"png" | "apng" => Self::Png,
"jpg" | "jpeg" => Self::Jpeg,
"gif" => Self::Gif,
"bmp" => Self::Bmp,
"tiff" => Self::Tiff,
"webp" => Self::WebP,
_ => Self::Unknown,
},
)
}
/// Returns the format specified by the given path.
///
/// This uses [`ImageFormat::from_extension`] to parse the extension.
///
/// This resolves via the extension of the path. See [`ImageFormat::infer_encoding`] for an
/// implementation that can resolve the format from the data.
///
/// # Errors
/// * No extension can be resolved from the path.
pub fn from_path(path: impl AsRef<Path>) -> Result<Self> {
path.as_ref()
.extension()
.ok_or_else(|| InvalidExtension(path.as_ref().into()))
.and_then(Self::from_extension)
}
/// Returns the format specified by the given MIME type.
pub fn from_mime_type(mime: impl AsRef<str>) -> Self {
let mime = mime.as_ref();
match mime {
"image/png" => Self::Png,
"image/jpeg" => Self::Jpeg,
"image/gif" => Self::Gif,
"image/bmp" => Self::Bmp,
"image/tiff" => Self::Tiff,
"image/webp" => Self::WebP,
_ => Self::Unknown,
}
}
/// Infers the encoding format from the given data via a byte stream.
#[must_use]
pub fn infer_encoding(sample: &[u8]) -> Self {
if sample.starts_with(b"\x89PNG\x0D\x0A\x1A\x0A") {
Self::Png
} else if sample.starts_with(b"\xFF\xD8\xFF") {
Self::Jpeg
} else if sample.starts_with(b"GIF") {
Self::Gif
} else if sample.starts_with(b"BM") {
Self::Bmp
} else if sample.len() > 11 && &sample[8..12] == b"WEBP" {
Self::WebP
} else if (sample.starts_with(b"\x49\x49\x2A\0") || sample.starts_with(b"\x4D\x4D\0\x2A"))
&& sample[8] != 0x43
&& sample[9] != 0x52
{
Self::Tiff
} else {
Self::Unknown
}
}
/// Encodes the `Image` into raw bytes.
///
/// # Errors
/// * An error occured while encoding.
///
/// # Panics
/// * No encoder implementation is found for this image encoding.
#[cfg_attr(
not(any(feature = "png", feature = "gif", feature = "jpeg", feature = "webp")),
allow(unused_variables, unreachable_code)
)]
pub fn run_encoder<P: Pixel>(&self, image: &Image<P>, dest: impl Write) -> Result<()> {
match self {
#[cfg(feature = "png")]
Self::Png => png::PngEncoder::encode_static(image, dest),
#[cfg(feature = "jpeg")]
Self::Jpeg => jpeg::JpegEncoder::encode_static(image, dest),
#[cfg(feature = "gif")]
Self::Gif => gif::GifEncoder::encode_static(image, dest),
#[cfg(feature = "webp")]
Self::WebP => webp::WebPStaticEncoder::encode_static(image, dest),
_ => panic!(
"No encoder implementation is found for this image format. \
Did you forget to enable the feature?"
),
}
}
/// Encodes the `ImageSequence` into raw bytes. If the encoding does not supported image
/// sequences (or multi-frame images), it will only encode the first frame.
///
/// # Errors
/// * An error occured while encoding.
///
/// # Panics
/// * No encoder implementation is found for this image encoding.
#[cfg_attr(
not(any(feature = "png", feature = "gif", feature = "jpeg", feature = "webp")),
allow(unused_variables, unreachable_code)
)]
pub fn run_sequence_encoder<P: Pixel>(
&self,
seq: &crate::ImageSequence<P>,
dest: impl Write,
) -> Result<()> {
match self {
#[cfg(feature = "png")]
Self::Png => png::PngEncoder::encode_sequence(seq, dest),
#[cfg(feature = "jpeg")]
Self::Jpeg => jpeg::JpegEncoder::encode_sequence(seq, dest),
#[cfg(feature = "gif")]
Self::Gif => gif::GifEncoder::encode_sequence(seq, dest),
#[cfg(feature = "webp")]
Self::WebP => webp::WebPMuxEncoder::encode_sequence(seq, dest),
_ => panic!(
"No encoder implementation is found for this image format. \
Did you forget to enable the feature?"
),
}
}
/// Decodes the image data from into an image.
///
/// # Errors
/// * An error occured while decoding.
///
/// # Panics
/// * No decoder implementation is found for this image encoding.
#[cfg_attr(
not(any(feature = "png", feature = "gif", feature = "jpeg", feature = "webp")),
allow(unused_variables, unreachable_code)
)]
#[allow(clippy::needless_pass_by_value)] // would require a major refactor
pub fn run_decoder<P: Pixel>(&self, stream: impl Read) -> Result<Image<P>> {
match self {
#[cfg(feature = "png")]
Self::Png => png::PngDecoder::new().decode(stream),
#[cfg(feature = "jpeg")]
Self::Jpeg => jpeg::JpegDecoder::new().decode(stream),
#[cfg(feature = "gif")]
Self::Gif => gif::GifDecoder::new().decode(stream),
#[cfg(feature = "webp")]
Self::WebP => webp::WebPDecoder::default().decode(stream),
_ => panic!(
"No encoder implementation is found for this image format. \
Did you forget to enable the feature?"
),
}
}
/// Decodes the image sequence data into an image sequence.
///
/// # Errors
/// * An error occured while decoding.
///
/// # Panics
/// * No decoder implementation is found for this image encoding.
#[cfg_attr(
not(any(feature = "png", feature = "gif", feature = "jpeg", feature = "webp")),
allow(unused_variables, unreachable_code)
)]
#[allow(clippy::needless_pass_by_value)] // would require a major refactor
pub fn run_sequence_decoder<'a, P: Pixel + 'a, R: Read + 'a>(
&self,
stream: R,
) -> Result<Box<dyn FrameIterator<P> + 'a>> {
Ok(match self {
#[cfg(feature = "png")]
Self::Png => Box::new(png::PngDecoder::new().decode_sequence(stream)?),
#[cfg(feature = "jpeg")]
Self::Jpeg => Box::new(jpeg::JpegDecoder::new().decode_sequence(stream)?),
#[cfg(feature = "gif")]
Self::Gif => Box::new(gif::GifDecoder::new().decode_sequence(stream)?),
#[cfg(feature = "webp")]
Self::WebP => Box::new(webp::WebPDecoder::default().decode_sequence(stream)?),
_ => panic!(
"No encoder implementation is found for this image format. \
Did you forget to enable the feature?"
),
})
}
}
impl Display for ImageFormat {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}",
match self {
Self::Png => "png",
Self::Jpeg => "jpeg",
Self::Gif => "gif",
Self::Bmp => "bmp",
Self::Tiff => "tiff",
Self::WebP => "webp",
Self::Unknown => "",
}
)
}
}