how to save a subimage in Rust?

Viewed 479

I got a subimage from an image in Rust. Though the document seems to list no way to save a subimage conveniently. Do I have to read each pixel to write to a buffer?

Here follows my code in Playground.

fn main() {
    
    f();
}
fn f(){
let (w,h)=(100,100);
for (x,y) in &[(100 as u32,200 as u32)]{
         let mut img = image::open("mySvg.png").unwrap();
         let subimg = imageops::crop(&mut img, *x , *y , w , h );
         let mut output = std::fs::File::create(format!("mySvg.{}.{}.png",x,y).as_str()).unwrap();
         subimg.write_to(&mut output, ImageFormat::Png).unwrap(); //Error!!
}}
 no method named `write_to` found for struct `SubImage<&mut DynamicImage>` in the current scope
  --> src/main.rs:12:17
   |
12 |          subimg.write_to(&mut output, ImageFormat::Png).unwrap(); //Error!!
   |                 ^^^^^^^^ method not found in `SubImage<&mut DynamicImage>`
1 Answers

The method write_to is not implemented for SubImage.

However, the method SubImage::to_image is available, which returns an ImageBuffer.

One can then use ImageBuffer::save_with_format to write out the file.

I've used an image of Ferris and the following directory structure:

.  stackoverflow_save_subimage
├─ Cargo.lock
├─ Cargo.toml
├─ ferris.png
├─ src/
│  └─ main.rs
└─ target/
use image::*;

fn main() {
    let (w, h) = (100, 100);

    for &(x, y) in &[(100, 200)] {
        let mut img = image::open("ferris.png").unwrap();
        let sub_img = imageops::crop(&mut img, x, y, w, h);
        let path = format!("ferris_crop.{}.{}.png", x, y);
        sub_img
            .to_image()
            .save_with_format(&path, ImageFormat::Png)
            .unwrap();
    }
}

Running the above generates the following cropped ferris_crop.100.200.png:

The cropped output of ferris.png

Related