image_meta/
loader.rs

1use std::fs::File;
2use std::io::{BufRead, BufReader, Seek, SeekFrom};
3use std::path::Path;
4
5pub mod bmp;
6pub mod gif;
7pub mod hdr;
8pub mod jpeg;
9pub mod png;
10mod riff;
11pub mod webp;
12
13use crate::errors::ImageError::InvalidSignature;
14use crate::errors::{ImageError, ImageResult};
15use crate::types::{Format, ImageMeta};
16
17macro_rules! try_to_load {
18    ($image_type:ident, $image:ident) => {
19        match $image_type::load($image) {
20            Ok(meta) => return Ok(meta),
21            Err(InvalidSignature) => {
22                $image.seek(SeekFrom::Start(0))?;
23            }
24            otherwise => return otherwise,
25        }
26    };
27}
28
29pub fn load<R: ?Sized + BufRead + Seek>(image: &mut R) -> ImageResult<ImageMeta> {
30    try_to_load!(jpeg, image);
31    try_to_load!(gif, image);
32    try_to_load!(png, image);
33    try_to_load!(bmp, image);
34    try_to_load!(webp, image);
35    try_to_load!(hdr, image);
36    Err(ImageError::Unsupported)
37}
38
39pub fn load_from_buf(buffer: &[u8]) -> ImageResult<ImageMeta> {
40    let mut buffer = std::io::Cursor::new(buffer);
41    load(&mut buffer)
42}
43
44pub fn load_from_file<T: ?Sized + AsRef<Path>>(file: &T) -> ImageResult<ImageMeta> {
45    let file = File::open(file.as_ref())?;
46    let mut file = BufReader::new(file);
47    load(&mut file)
48}
49
50pub fn load_with_format<R: ?Sized + BufRead + Seek>(
51    image: &mut R,
52    format: Format,
53) -> ImageResult<ImageMeta> {
54    use Format::*;
55
56    match format {
57        Bmp => bmp::load(image),
58        Gif => gif::load(image),
59        Jpeg => jpeg::load(image),
60        Png => png::load(image),
61        Webp => webp::load(image),
62        Hdr => hdr::load(image),
63    }
64}