Alex Rivera | Logout

Java get image extension/type using BufferedImage from URL

Asked 2012-07-12T07:34:01.850
34

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.

Edit
Report

1 Answer

40

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());
}
answered 2012-07-12T07:38:55.900

Your Answer