Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NPE in JPEGImageReader.getSourceCSType in case of mime mixup #96

Closed
huxi opened this issue Feb 19, 2015 · 2 comments
Closed

NPE in JPEGImageReader.getSourceCSType in case of mime mixup #96

huxi opened this issue Feb 19, 2015 · 2 comments
Assignees

Comments

@huxi
Copy link

huxi commented Feb 19, 2015

This is a followup to my comment in issue #22.

The exception is thrown with the following stack trace:

com.twelvemonkeys.imageio.plugins.jpeg.JPEGImageReader.getSourceCSType(Unknown Source)
com.twelvemonkeys.imageio.plugins.jpeg.JPEGImageReader.read(Unknown Source)
javax.imageio.ImageReader.read(ImageReader.java:939)

The code causing the issue looks like this:

ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(inputStream));
Iterator readers = ImageIO.getImageReadersByMIMEType(mimeType);
ImageReader imageReader = (ImageReader) readers.next();
imageReader.setInput(iis, false);
BufferedImage bufferedImage = imageReader.read(0);

The mimeType is resolved by us based on the file extension so this is essentially our fault.

I thought I'd file this issue anyway so that other people hitting a similar problem can find it.

Is there a better way to create a BufferedImage from an InputStream, i.e. one that would resolve the actual mime type instead of using an inferred one to resolve the proper ImageReader?

@haraldk haraldk self-assigned this Feb 19, 2015
@haraldk
Copy link
Owner

haraldk commented Feb 19, 2015

Hi Jörn,

Thanks for reporting!

I think the recommended way of obtaining an ImageReader is as follows:

ImageInputStream input = ImageIO.createInputStream(...);
Iterator<ImageReader> readers = ImageIO.getImageReaders(input);

if (readers.hasNext()) {
    ImageReader reader = readers.next();
    reader.setInput(input);

    // etc...
}

This way, each plugin provider (ImageReaderSpi instance) will be passed the actual payload (input in the example above), to see if this is a format it understands, and if so, it can create an ImageReader instance to read it.

I prefer this way, because file extensions can be wrong and there are often multiple extensions for each format. MIME types from browsers can also not be fully trusted. Inspecting the actual payload is just safer and more reliable (although there can be false positives here as well).

Best regards,

Harald K

@haraldk haraldk closed this as completed Feb 19, 2015
@huxi
Copy link
Author

huxi commented Feb 19, 2015

Thanks a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants