【问题标题】:Rust open image with other format than file extension使用除文件扩展名以外的其他格式打开图像
【发布时间】:2022-02-04 19:11:19
【问题描述】:

我正在尝试在我的 Rust 程序中打开一个图像。该图像被命名为 foo.png,但它不会打开带有image::open("foo.png") 的图像。 如果我将文件重命名为 foo.jpeg,我可以打开图像,所以我的猜测是格式和文件扩展名不匹配。

那么我的问题是。如何打开名为 foo.png 的文件,但将其解码为 jpeg? 我试过image::io::Reader,但我似乎无法让它正常工作。

【问题讨论】:

  • 您可以检查文件的前几个字节的magic bytes,然后根据检测到的格式使用适当的解码函数。

标签: image rust image-formats


【解决方案1】:

您可以使用image::load() 函数,它可以让您指定格式:

let image = image::load(BufReader::new(File::open("foo.png")?), ImageFormat::Jpeg)?;

【讨论】:

  • 如果我这样做,我会收到错误“无法在返回 ()" If I remove the "?" i get the error "the trait Seek` 的函数中使用 ? 运算符,而不会为 Result<File, std::io::Error> 实现”
  • "cannot use the ? operator in a function that return ()" 是另一个错误,如果这部分 Rust 书 - doc.rust-lang.org/book/… - 对你没有帮助,它可能需要另一个问题(很可能会因为重复而关闭,但我现在找不到证据)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-20
  • 2021-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多