【问题标题】:Java check if BufferedImage is a GIFJava 检查 BufferedImage 是否为 GIF
【发布时间】:2011-05-12 14:35:44
【问题描述】:

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

谢谢

【问题讨论】:

    标签: java gif bufferedimage


    【解决方案1】:

    从 URL 中读取第一个字节,如果是 GIF 图片,它应该以 'magic word' 开头:GIF89a

    【讨论】:

      【解决方案2】:

      下面的代码会告诉你图片流的格式是什么

      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

      【讨论】:

        猜你喜欢
        • 2013-01-07
        • 2018-02-05
        • 2013-06-12
        • 1970-01-01
        • 1970-01-01
        • 2014-10-25
        • 2014-04-08
        • 2012-12-18
        相关资源
        最近更新 更多