0

I want to merge two images. I'm using image::imageops::overlay from the image crate:

use image::imageops::overlay;
use std::path::Path;

fn main() {
    let path1 = Path::new("~/Desktop/to-merge/image1.png");
    let path2 = Path::new("~/Desktop/to-merge/image2.png");
    let mut img1 = image::open(&path1).unwrap().clone();
    let mut img2 = image::open(&path2).unwrap().clone();
    let output = overlay(&mut img1, &mut img2, 0, 0);
    let save_path = Path::new("~/Desktop/to-crop/merged.png");
    output.save(save_path).unwrap();
}

After hitting cargo run, I get this error:

error[E0599]: no method named `save` found for unit type `()` in the current scope
--> src/main.rs:11:12
   |
11 |     output.save(save_path).unwrap();
   |            ^^^^ method not found in `()`

I think the compiler is saying image::imageops::overlay doesn't have the method save()? If so, what should I use instead?

Playground

cafce25
  • 15,907
  • 4
  • 25
  • 31
alexchenco
  • 53,565
  • 76
  • 241
  • 413

1 Answers1

5

image::imageops::overlay mutates the image passed as the first argument, overlaying the second image on it, and returns (). You need to call .save() on img1 since that image now has img2 overlayed on it. Also, you don't need to pass a mutable reference to img2 to overlay and the .clone() calls are unnecessary.

use image::imageops::overlay;
use std::path::Path;

fn main() {
    let path1 = Path::new("~/Desktop/to-crop/image1.png");
    let path2 = Path::new("~/Desktop/to-crop/image2.png");
    let mut img1 = image::open(&path1).unwrap();
    let img2 = image::open(&path2).unwrap();
    overlay(&mut img1, &img2, 0, 0);
    let save_path = Path::new("~/Desktop/to-crop/merged.png");
    img1.save(save_path).unwrap();
}

Also, ~ will not be expanded by Rust automatically, so you need to pass the full path to the images. See this question.


Creating a Path is also unnecessary since both the functions accept P: AsRef<Path>, which means you can pass &str directly:

use image::imageops::overlay;
use std::path::Path;

fn main() {
    let path1 = "~/Desktop/to-crop/image1.png";
    let path2 = "~/Desktop/to-crop/image2.png";
    let mut img1 = image::open(&path1).unwrap();
    let img2 = image::open(&path2).unwrap();
    overlay(&mut img1, &img2, 0, 0);
    let save_path = "~/Desktop/to-crop/merged.png";
    img1.save(save_path).unwrap();
}
Dogbert
  • 212,659
  • 41
  • 396
  • 397