Esteban Borai
Esteban Borai

Reputation: 2509

Rust: Encode a JPEG image into a PNG using image-rs

I'm using the image (Link to repo) crate in Rust, to encode a GIF image into a PNG with the following code:

  fn encode_png(&self, img: &DynamicImage) -> Result<(), Error> {
    let file = File::create("icon.png").unwrap();
    let ref mut buff = BufWriter::new(file);
    let encoder = PNGEncoder::new(buff);

    match encoder.encode(&img.to_bytes(), 256, 256, img.color()) {
      Ok(_) => Ok(()),
      Err(err) => Err(Error::new(err.description()))
    }
  }

The img variable represents a DynamicImage which I opened using the open method from the same crate.

What happens is, that the programs runs successfuly but the output file is broken. I wrote the code based on the following docs: PNGEncoder | encode

Thanks in advance!

Upvotes: 1

Views: 2358

Answers (1)

Esteban Borai
Esteban Borai

Reputation: 2509

The issue with my code above is that I'm giving the wrong image dimensions to the encoder as parameters (256, 256).

I expected the image to be resized to 256x256 but the encoder expects the current image dimensions in order to work as expected.

The following code is running as expected:

  fn encode_png(&self, img: &DynamicImage) -> Result<(), Error> {
    let file = File::create("icon.png").unwrap();
    let ref mut buff = BufWriter::new(file);
    let encoder = PNGEncoder::new(buff);

    match encoder.encode(&img.to_bytes(), img.dimensions().0, img.dimensions().1, img.color()) {
      Ok(_) => Ok(()),
      Err(err) => Err(Error::new(err.description()))
    }
  }

Thanks to Solomon Ucko for pointing it out in the comments!

As I needed to resize the image and then encode it to a PNG file, I ended up with the following:

  fn encode_png(&self, img: &DynamicImage) -> Result<(), Error> {
    if img.dimensions().0 != 256 {
      let resized = img.resize_exact(256, 256, FilterType::Gaussian);

      return self.encode_png(&resized);
    }

    let file = File::create("icon.png").unwrap();
    let ref mut buff = BufWriter::new(file);
    let encoder = PNGEncoder::new(buff);

    match encoder.encode(&img.to_bytes(), img.dimensions().0, img.dimensions().1, img.color()) {
      Ok(_) => Ok(()),
      Err(err) => Err(Error::new(err.description()))
    }
  }

Upvotes: 1

Related Questions