Java get image extension/type using BufferedImage from URL

image, java

Solution

Use ImageReader.getFormatName()

You can get the image readers for a file using ImageIO.getImageReaders(Object input).

I haven't tested it myself, but you can try this:

ImageInputStream iis = ImageIO.createImageInputStream(file);

Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(iis);

while (imageReaders.hasNext()) {
    ImageReader reader = (ImageReader) imageReaders.next();
    System.out.printf("formatName: %s%n", reader.getFormatName());
}

Problem

I am familiar with working with images. I retrieve/read an image from a URL, where the URL does not have a file extension. Then I wish to write/save the image to the local storage, but I have to specify the image file extension (i.e. JPG, PNG, etc.), which I cannot retrieve its extension through the BufferedImage. Could one please point out how it can be done? Any other method will do.

Original source