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 necessary functionality to work with images in Rust. We can combine functionality provided by the crate with the path module from Rusts 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 csv 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::io::Reader;

fn get_image_dimensions(file_path: &str) -> Result<(u32, u32)> {
    let path = Path::new(file_path);
    let reader = Reader::open(path)?;
    let dimensions = reader.into_dimensions()?;
    Ok(dimensions)
}

The get_image_dimensions function takes a file path as an argument and returns a tuple of the image dimensions in the form of (u32, u32).

It first creates a Path object from the provided file path. It then uses the Reader type from the image crate to read 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. 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.

We can call the get_image_dimensions method like shown here:

fn main() {
    match get_image_dimensions("data/sample.jpg") {
        Ok((width, height)) => println!("dimensions: {} x {}", width, height),
        Err(e) => println!("error: {}", e),
    }
}