简体   繁体   English

Rust:使用 image-rs 将 JPEG 图像编码为 PNG

[英]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:我正在使用 Rust 中的image链接到 repo )板条箱,使用以下代码将 GIF 图像编码为 PNG:

  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. img变量表示我使用open方法从同一个 crate 打开的DynamicImage

What happens is, that the programs runs successfuly but the output file is broken.发生的情况是,程序运行成功,但 output 文件已损坏。 I wrote the code based on the following docs: PNGEncoder |我根据以下文档编写了代码: PNGEncoder | encode 编码

Thanks in advance!提前致谢!

The issue with my code above is that I'm giving the wrong image dimensions to the encoder as parameters (256, 256).我上面的代码的问题是我给编码器提供了错误的图像尺寸作为参数(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.我希望将图像大小调整为 256x256,但编码器希望当前图像尺寸能够按预期工作。

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!感谢Solomon Ucko在评论中指出!

As I needed to resize the image and then encode it to a PNG file, I ended up with the following:由于我需要调整图像大小然后将其编码为 PNG 文件,因此我得到了以下结果:

  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()))
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM