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
use bytes::Bytes;
use crate::encoder::{EncodeAt, ImageEncoder};
use crate::jpeg::{is_jpeg, Jpeg};
use crate::png::{is_png, Png};
use crate::webp::{is_webp, WebP};
use crate::{ImageEXIF, ImageICC, Result};
#[derive(Debug)]
pub enum DynImage {
Jpeg(Jpeg),
Png(Png),
WebP(WebP),
}
#[allow(clippy::len_without_is_empty)]
impl DynImage {
pub fn from_bytes(b: Bytes) -> Result<Option<DynImage>> {
if is_jpeg(&b) {
let jpeg = Jpeg::from_bytes(b)?;
Ok(Some(jpeg.into()))
} else if is_png(&b) {
let png = Png::from_bytes(b)?;
Ok(Some(png.into()))
} else if is_webp(&b) {
let webp = WebP::from_bytes(b)?;
Ok(Some(webp.into()))
} else {
Ok(None)
}
}
pub fn len(&self) -> usize {
match self {
Self::Jpeg(jpeg) => jpeg.len(),
Self::Png(png) => png.len(),
Self::WebP(webp) => webp.len() as usize,
}
}
#[inline]
pub fn encoder(self) -> ImageEncoder<Self> {
ImageEncoder::from(self)
}
}
impl EncodeAt for DynImage {
fn encode_at(&self, pos: &mut usize) -> Option<Bytes> {
match self {
Self::Jpeg(jpeg) => jpeg.encode_at(pos),
Self::Png(png) => png.encode_at(pos),
Self::WebP(webp) => webp.inner().encode_at(pos),
}
}
fn len(&self) -> usize {
self.len()
}
}
impl ImageICC for DynImage {
fn icc_profile(&self) -> Option<Bytes> {
match self {
Self::Jpeg(jpeg) => jpeg.icc_profile(),
Self::Png(png) => png.icc_profile(),
Self::WebP(webp) => webp.icc_profile(),
}
}
fn set_icc_profile(&mut self, profile: Option<Bytes>) {
match self {
Self::Jpeg(jpeg) => jpeg.set_icc_profile(profile),
Self::Png(png) => png.set_icc_profile(profile),
Self::WebP(webp) => webp.set_icc_profile(profile),
}
}
}
impl ImageEXIF for DynImage {
fn exif(&self) -> Option<Bytes> {
match self {
Self::Jpeg(jpeg) => jpeg.exif(),
Self::Png(png) => png.exif(),
Self::WebP(webp) => webp.exif(),
}
}
fn set_exif(&mut self, exif: Option<Bytes>) {
match self {
Self::Jpeg(jpeg) => jpeg.set_exif(exif),
Self::Png(png) => png.set_exif(exif),
Self::WebP(webp) => webp.set_exif(exif),
}
}
}
impl From<Jpeg> for DynImage {
#[inline]
fn from(jpeg: Jpeg) -> DynImage {
DynImage::Jpeg(jpeg)
}
}
impl From<Png> for DynImage {
#[inline]
fn from(png: Png) -> DynImage {
DynImage::Png(png)
}
}
impl From<WebP> for DynImage {
#[inline]
fn from(webp: WebP) -> DynImage {
DynImage::WebP(webp)
}
}