Is there a way to determine image format from a random file?

时间:2016-08-31 18:25:52

标签: java image javax.imageio

I'm using javas jai libraries and trying to figure out a way to determine correct format of a picture when a random file is given, such as image.qwe. The solution given for example here: http://www.java2s.com/Tutorial/Java/0261__2D-Graphics/DeterminingtheFormatofanImageinaFile.htm works well if the file is in right format, like image.jpg. But if an actual picture image.jpg is renamed to image.qwe, ImageIO.getImageReaders() returns an empty iterator.

Is this correct behaviour or should it be able to deduce that the file is actually jpg format?

2 个答案:

答案 0 :(得分:4)

Your best bet is to use Files.probeContentType() to determine the type of the file based on its content.

This will work regardless of whether it's been renamed. As long as you're not working with such exotic types that the readers don't understand the file, it gives you an easy way to probe the file data and determine the file type.

答案 1 :(得分:0)

试试这个:

    BufferedImage originalImage = ImageIO.read(inputStream);
    int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB
            : originalImage.getType();

以下是TYPE_INT_ARGB的说明: 表示将8位RGBA颜色分量打包为整数像素的图像。该图像具有带alpha的DirectColorModel。该图像中的颜色数据被认为不与alpha预乘。当此类型用作BufferedImage构造函数的imageType参数时,创建的图像与在JDK1.1和早期版本中创建的图像一致。

相关问题