Working with Images in Rust: resize and crop with the image library

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Working with Images in Rust: resize and crop with the image library



Rust is a modern systems programming language that is gaining popularity in tasks requiring high performance and safety. One such task is image processing. In this article, we will take a detailed look at how to resize and crop images in Rust using the powerful and convenient image library. You will learn how to install the library, load an image, apply transformations, and save the result.



Installing and including the image library



The image library is the de facto standard for working with raster images in the Rust ecosystem. It supports many formats (PNG, JPEG, GIF, BMP, WEBP, and others) and provides a wide range of processing functions.



To get started, add the dependency to your Cargo.toml file:



[dependencies]image = "0.25"


After that, you can import the necessary modules in your code:



use std::path::Path;use image::{open, DynamicImage, GenericImageView, imageops::FilterType};


Loading and saving images



The first step is to load an image from a file. The library will automatically detect the format based on the extension. Let's look at a basic example:



fn main() -> Result<(), Box<dyn std::error::Error>> {    // Load the image    let img = open("input.jpg")?;    println!("Dimensions: {:?}", img.dimensions());    // Save in a different format    img.save("output.png")?;    Ok(())}


The open() method returns a DynamicImage — an enum that can store an image in one of several internal formats (RGB8, RGBA8, Gray8, etc.). The dimensions() method returns a tuple (u32, u32) — the width and height.



Resizing (resize)



The resize() function takes a new width, height, and filter type. The filter affects the quality of the result and the execution speed. Here are the main filters:



  • Nearest — fast, but low quality (pixelation).
  • Lanczos3 — high quality, but slower.
  • CatmullRom — a good balance of speed and quality.
  • Gaussian — blurs the image when downscaling.


Example of resizing to 800x600 pixels:



use image::imageops::FilterType;

fn resize_example() -> Result<(), Box<dyn std::error::Error>> { let img = open("input.jpg")?; let resized = img.resize(800, 600, FilterType::Lanczos3); resized.save("resized.jpg")?; println!("New dimensions: {:?}", resized.dimensions()); Ok(())}


If you need to preserve the aspect ratio, use resize_to_fill() (fills the area, cropping excess) or resize_to_fit() (fits within the given dimensions, adding empty space). Example:



// Fit into a 400x400 rectangle, preserving aspect ratiolet fitted = img.resize_to_fit(400, 400, FilterType::CatmullRom);fitted.save("fitted.jpg")?;

// Fill a 400x400 rectangle, cropping the edgeslet filled = img.resize_to_fill(400, 400, FilterType::Lanczos3);filled.save("filled.jpg")?;


Cropping an image (crop)



Cropping is done using the crop() method, which takes the coordinates of the top-left corner (x, y), as well as the width and height of the area. Important: the coordinates and dimensions must not exceed the boundaries of the original image, otherwise a panic will occur.



Example of cropping a central area of size 300x200:



fn crop_example() -> Result<(), Box<dyn std::error::Error>> {    let img = open("input.jpg")?;    let (width, height) = img.dimensions()                    

Recommendations