How to get the format(ex:jpen,png,gif) of image file (BufferedImage) in java

VICKY-TSC picture VICKY-TSC · Jul 11, 2012 · Viewed 18.6k times · Source

i want to get the buffered image format or type of image using java,

 InputStream stream = request.getResponseStream();   
 BufferedImage image=  ImageIO.read(stream);
 LOGGER.info(image);

Answer

dgregory picture dgregory · Jul 20, 2015

Refer the javax.imageio.ImageIO.read() code

This code originally implemented in groovy but translated into java so It may have a syntax error.

public String read(InputStream input) throws IOException {
    ImageInputStream stream = ImageIO.createImageInputStream(input);

    Iterator iter = ImageIO.getImageReaders(stream);
    if (!iter.hasNext()) {
        return null;
    }
    ImageReader reader = (ImageReader) iter.next();
    ImageReadParam param = reader.getDefaultReadParam();
    reader.setInput(stream, true, true);
    BufferedImage bi;
    try {
        bi = reader.read(0, param);
        return reader.getFormatName();
    } finally {
        reader.dispose();
        stream.close();
    }
}