imghdr/std_ext.rs
1use std::fs::File;
2use std::io::{Read, Result};
3use std::path::Path;
4
5use super::{patterns, Type};
6
7/// Try to determine image format from an IO stream of bytes.
8///
9/// Available only with `std` feature (enabled by default).
10///
11/// ## Returns
12///
13/// * `Ok(Some(Type))` if it is a known image format
14/// * `Ok(None)` if it is probably not an image
15/// * `Err(..)` if failed to read minimal bytes amount for a guess
16///
17/// # Examples
18///
19/// ```rust
20/// # use std::fs::File;
21/// # use std::io::{Result, Read};
22/// # fn main() -> Result<()> {
23/// let mut file = File::open("./tests/images/example.png")?;
24/// println!("{:?}", imghdr::from_reader(file));
25/// # Ok(())
26/// # }
27/// ```
28pub fn from_reader<T: Read>(mut f: T) -> Result<Option<Type>> {
29 let mut buffer = [0; patterns::MAX_LENGTH];
30 f.read_exact(&mut buffer)?;
31
32 Ok(crate::from_bytes(&buffer))
33}
34
35/// Open file and try to determine if it is an image.
36///
37/// Available only with `std` feature (enabled by default).
38///
39/// # Errors
40///
41/// This function will return an `Err(std::io::Error)` if file is inaccessible or can't be read.
42///
43/// # Examples
44///
45/// ```rust
46/// let result = imghdr::from_file("./tests/images/example.jpg");
47///
48/// println!("{:#?}", result);
49/// ```
50pub fn from_file<T: AsRef<Path>>(path: T) -> Result<Option<Type>> {
51 let file = File::open(path)?;
52
53 from_reader(file)
54}