2010-11-19 78 views

回答

4

從URL中讀取的第一個字節,如果它是一個GIF圖像,它應該用「神奇的詞」開始:GIF89a

+0

老版本有'GIF87a',如果我沒有記錯 – 2010-11-19 12:39:26

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