This article introduces how to capture screenshots with Rust. We’ll capture the entire screen and save images to a specified folder.
To capture screenshots with Rust, it’s common to use a crate called screenshots - crates.io: Rust Package Registry.
Capturing Screenshots with Rust
First, add the following to Cargo.toml.
This allows you to use the screenshots crate.
screenshots = "0.8.6"
The overall code looks like this.
This defines a function called screenshot() that captures a screenshot.
use screenshots::Screen;
use std::time::Instant;
// screenshot(dest) -> void
fn screenshot(dest: &str) {
let start = Instant::now();
let screens = Screen::all().unwrap();
for screen in screens {
println!("capturer {screen:?}");
let mut image = screen.capture().unwrap();
image
.save(format!("{}", dest))
.unwrap();
}
println!("screenshot took {}ms", start.elapsed().as_millis());
}
The execution flow of this function is as follows:
use screenshots::Screen;: Enable use of theScreenstruct from thescreenshotscrateuse std::time::Instant;: Enable use of theInstantstruct fromstd’stimefn screenshot(dest: &str) {: Define a function calledscreenshot. The argument is a string type calleddestlet start = Instant::now();: Assign the current time to a variable calledstartlet screens = Screen::all().unwrap();: Assign all screens to a variable calledscreensfor screen in screens {: Assign the contents ofscreensto a variable calledscreenand looplet mut image = screen.capture().unwrap();: Capture a screenshot ofscreenand assign it to a variable calledimageimage.save(format!("{}", dest)).unwrap();: Saveimagewith the filenamedestprintln!("screenshot took {}ms", start.elapsed().as_millis());: Display the time it took to capture the screenshot
That’s all.
This function can be called as follows:
screenshot("screenshot.png");
Or it can also be called as follows:
screenshot("./path/to/screenshot.png");
Summary
This article introduced how to capture screenshots with Rust.