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
use image::{DynamicImage, RgbImage};
pub use libavif::is_avif;
use libavif::AvifData;
pub fn read(buf: &[u8]) -> Result<DynamicImage, String> {
let pixels = libavif::decode_rgb(buf).map_err(|e| format!("decoding AVIF: {}", e))?;
let mut img = RgbImage::new(pixels.width(), pixels.height());
for y in 0..img.height() {
for x in 0..img.width() {
let (r, g, b, _a) = pixels.pixel(x, y);
img.put_pixel(x, y, [r, g, b].into());
}
}
Ok(DynamicImage::ImageRgb8(img))
}
pub fn save(img: &DynamicImage) -> Result<AvifData, String> {
let data = match img {
DynamicImage::ImageRgb8(img) => {
let rgb = img.as_flat_samples();
libavif::encode_rgb8(img.width(), img.height(), rgb.as_slice())
.map_err(|e| format!("encoding AVIF: {:?}", e))?
}
_ => return Err("image type not supported".into()),
};
Ok(data)
}