nashaofu / xcap

XCap is a cross-platform screen capture library written in Rust. It supports Linux (X11, Wayland), MacOS, and Windows. XCap supports screenshot and video recording (to be implemented).
https://docs.rs/xcap
Apache License 2.0
459 stars 55 forks source link

[Question]: How to capture area of window or screen? #102

Closed cdrani closed 7 months ago

cdrani commented 7 months ago

I'm not sure how to capture only a defined section window or monitor. Looking through the issues, there seemed to previously exist a capture_area method, but not implemented here. Perhaps I should use an older release prior to the refactor and name change?

nashaofu commented 7 months ago

I feel capture_area can be implemented in other ways, and is not limited by the platform,so it moves in this PR, You can use the following code to crop image

use std::time::Instant;
use xcap::{image::DynamicImage, Monitor};

fn normalized(filename: &str) -> String {
    filename
        .replace("|", "")
        .replace("\\", "")
        .replace(":", "")
        .replace("/", "")
}

fn main() {
    let start = Instant::now();
    let monitors = Monitor::all().unwrap();

    for monitor in monitors {
        let image = monitor.capture_image().unwrap();

        DynamicImage::from(image)
            .crop(10, 10, 100, 100)
            .save(format!("target/monitor-{}.png", normalized(monitor.name())))
            .unwrap();
    }

    println!("运行耗时: {:?}", start.elapsed());
}
cdrani commented 7 months ago

@nashaofu: Sorry about the late response. I ended up using the last version that still made use of the capture_area method. Will try this, but satisfied with the older api (for now). Thanks!