Java检查BufferedImage是否为GIF

时间:2010-11-19 12:09:44

标签: java gif bufferedimage

是否可以确定BufferedImage(从网址读取)是否为GIF图片?我想检查MIME类型,而不是文件扩展名.gif。

由于

2 个答案:

答案 0 :(得分:4)

读取网址中的第一个字节,如果是GIF图片,则应以“魔术字”开头:GIF89a

答案 1 :(得分:3)

以下代码将说明图像流的格式

public static 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);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        reader.dispose();
        try {
            stream.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return reader.getFormatName();
}

public static void main(String[] args) throws MalformedURLException, IOException {
    URL url = new URL("http://p1.pstatp.com/large/efa0004d2238045fb9f");
    URLConnection connection = url.openConnection();
    connection.setConnectTimeout(3000);
    connection.setReadTimeout(3000);
    InputStream in = null;
    try {
        in = connection.getInputStream();
        String format = read(in);
        System.out.print(format);
    } catch (Exception e) {

    }
}

输出结果为:

GIF