2

I am trying to open an image in my Rust program. The image is named foo.png, but it won't open the image with image::open("foo.png"). If I rename the file to foo.jpeg, I can open the image, so my guess is that the formatting and the file extension do not match.

My question is then. how do I open a file named foo.png, but decode it as a jpeg? I have tried image::io::Reader, but I can't seem to make it work properly.

trent
  • 25,033
  • 7
  • 51
  • 90
  • 1
    You can check the first few bytes of the file for its [magic bytes](https://en.wikipedia.org/wiki/List_of_file_signatures) then use the appropriate decoding function depending on the detected format. – Jmb Feb 04 '22 at 08:40

1 Answers1

2

You can use the image::load() function, which lets you specify the format:

let image = image::load(BufReader::new(File::open("foo.png")?), ImageFormat::Jpeg)?;
Brian Bowman
  • 892
  • 6
  • 9
  • If I do that I get the error "cannot use the `?` operator in a function that returns `()" If I remove the "?" i get the error "the trait `Seek` is not implemented for `Result`" – Kenneth Schmidt Feb 04 '22 at 09:55
  • 1
    "cannot use the ? operator in a function that returns ()" is another error, and if this part of Rust book - https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#a-shortcut-for-propagating-errors-the--operator - doesn't help you, it will possibly need another question (which is likely to be closed as duplicate, but I can't find proof for now). – Cerberus Feb 04 '22 at 10:48
  • https://stackoverflow.com/questions/58373663/cannot-use-the-operator-in-a-function-that-returns – Jmb Feb 04 '22 at 11:33