开发者

Java check if BufferedImage is a GIF

Is it possible to d开发者_运维问答etermine if a BufferedImage (read from an URL) is a GIF image? I want to check the MIME type, not the file extension .gif.

Thanks


read the very first bytes from the URL, if it's a GIF image, it should start with the 'magic word' : GIF89a


The following codes will tell what is the format of the image stream

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) {

    }
}

The output is:

gif

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜