Weekly Rust Trivia: How to Retrieve Image Dimensions
Weekly Rust Trivia is a problem-oriented series of articles that assist developers while learning Rust. Every article solves simple, everyday development tasks using the Rust standard library or leveraging popular and proven crates.
Question: How to retrieve the dimensions of an image in Rust?
The image crate provides the necessary functionality to work with images in Rust. We can combine functionality provided by the crate with the path module from Rust’s standard library to solve this trivia. We also use the anyhow crate to streamline error handling.
First, let’s add the following dependencies using cargo add:
# Add anyhow as dependency
cargo add anyhow
# Add the image crate as dependency
cargo add image
Having the crates added to our project, we can move on and implement inspecting an image to get its dimensions:
use std::path::Path;
use anyhow::Result;
use image::ImageReader;
fn get_image_dimensions(file_path: impl AsRef<Path>) -> Result<(u32, u32)> {
let reader = ImageReader::open(file_path)?;
let dimensions = reader.into_dimensions()?;
Ok(dimensions)
}
The get_image_dimensions function takes a file path (anything that can be referenced as a Path, such as a &str) as an argument and returns a tuple of the image dimensions in the form of (u32, u32).
It uses the ImageReader type from the image crate (formerly available as image::io::Reader) to open the image file at the provided path. The function then calls the into_dimensions() method on the reader to get the dimensions of the image. This reads only the image header and does not decode the entire image. If the operation is successful, it returns the dimensions in a tuple wrapped in a Result with the Ok variant. If there is an error, the function will return a Result with the Err variant.
Please note that ImageReader::open determines the image format from the file extension. If your files may have a missing or wrong extension, call with_guessed_format()? on the reader before into_dimensions() to detect the format based on the file contents.
We can call the get_image_dimensions method as shown here:
fn main() {
match get_image_dimensions("data/sample.jpg") {
Ok((width, height)) => println!("dimensions: {width} x {height}"),
Err(e) => println!("error: {e}"),
}
}
If you want to continue with Weekly Rust Trivia, check out these related articles: