开发者

ImageIO.createImageInputStream Keeps Returning null

开发者 https://www.devze.com 2023-02-13 11:59 出处:网络
Hey all, Whenever I try to get an ImageInputStream object using ImageIO.createImageInputStream it simply returns null with no exceptions, warnings or errors. I have tried passing different data types

Hey all, Whenever I try to get an ImageInputStream object using ImageIO.createImageInputStream it simply returns null with no exceptions, warnings or errors. I have tried passing different data types to the function, a simple File, and an InputStream, but both returned null also. The documentation says that if no suitable ImageInputStreamSpi is found then the function will return null, bu开发者_StackOverflow社区t the file is a bog-standard JPEG, and surely Java comes with a service provider for such a format out of the box? Thanks for your time.

/**
 * Reads in an image from a file and returns the image in a
 * {@code BufferedImage} object.
 *
 * @param source the file to create the {@code BufferedImage}
 * from.
 * @return the {@code BufferedImage} object representing the image
 * in {@code source}.
 */
private BufferedImage readImage( File source ) {
    // There is only one image in this file
    final int imageIndex = 0;
    BufferedImage image = null;

    try {
        // Get the ImageReader object for this filetype
        Iterator readers =
            ImageIO.getImageReaders( source );
        ImageReader reader = (ImageReader) readers.next();

        // Create an ImageInputStream object from the source image file
        ImageInputStream iis = ImageIO.createImageInputStream( source );
        // Raises IllegalArgumentException, because iis is null
        reader.setInput( iis, true );

        // Read the image file
        image = reader.read( imageIndex );
    } catch ( Exception exception ) {
        exception.printStackTrace();
        System.exit( -1 );
    }

    return image;
}


Why are you doing all that?? you can simply do this:

image = ImageIO.read(source);

No Iterators, ImageInputStreams... no nothing !

EDIT: Since you insist, your code is not working because you're sending a File to ImageIO.getImageReaders() instead of a ImageInputStream. SO your code should look something like that:

ImageInputStream iis = ImageIO.createImageInputStream(source);
Iterator readers = ImageIO.getImageReaders(iis);
ImageReader reader = (ImageReader) readers.next();

reader.setInput(iis, false);
image = reader.read(imageIndex);
0

精彩评论

暂无评论...
验证码 换一张
取 消