brendan-duncan / image

Dart Image Library for opening, manipulating, and saving various different image file formats.
MIT License
1.14k stars 254 forks source link

decodeImageFile error #636

Open equationl opened 3 months ago

equationl commented 3 months ago

I have a jpg file, but it's named "xx.png", when I try decode this file , I using decodeImageFile("xx.png"); . But get a null .

I check the code of decodeImageFile, it will get decoder by file name at findDecoderForNamedImage, in my case, it will use pngDecoder, of course it a mistake.

I find in pngDecoder, it will check file header:

    final pngHeader = _input.readBytes(8);
    const expectedHeader = [137, 80, 78, 71, 13, 10, 26, 10];
    for (var i = 0; i < 8; ++i) {
      if (pngHeader[i] != expectedHeader[i]) {
        return null;
      }
    }

If not png header, will return null.

So, why don't try another decoder if file header not match file name's extension?

Like change:

Future<Image?> decodeImageFile(String path, {int? frame}) async {
  final bytes = await readFile(path);
  if (bytes == null) {
    return null;
  }

  final decoder = findDecoderForNamedImage(path);
  if (decoder != null) {
-    return decoder.decode(bytes, frame: frame);
  }

  return decodeImage(bytes, frame: frame);
}

To:

Future<Image?> decodeImageFile(String path, {int? frame}) async {
  final bytes = await readFile(path);
  if (bytes == null) {
    return null;
  }

  final decoder = findDecoderForNamedImage(path);
  if (decoder != null) {
+    return decoder.decode(bytes, frame: frame) ?? decodeImage(bytes, frame: frame);
  }

  return decodeImage(bytes, frame: frame);
}

How about it?

brendan-duncan commented 3 months ago

Yeah, that's a fine suggestion. I just had that file open for another issue, so I pushed that change out.