2010-12-09 159 views
0

在Android上工作了1年後,我在傳統Java GUI中顯得有點生疏。JApplets:加載圖片

我需要知道在這樣兩件事情,我打開圖像

但首先一些代碼

/** 
    * Load the image for the specified frame of animation. Since 
    * this runs as an applet, we use getResourceAsStream for 
    * efficiency and so it'll work in older versions of Java Plug-in. 
    */ 
    protected ImageIcon loadImage(String imageNum, String extension) { 
     String path = dir + "/" + imageNum+"."+extension; 
     int MAX_IMAGE_SIZE = 2400000; //Change this to the size of 
     //your biggest image, in bytes. 
     int count = 0; 
     BufferedInputStream imgStream = new BufferedInputStream(
       this.getClass().getResourceAsStream(path)); 
     if (imgStream != null) { 
      byte buf[] = new byte[MAX_IMAGE_SIZE]; 
      try { 
       count = imgStream.read(buf); 
       imgStream.close(); 
      } catch (java.io.IOException ioe) { 
       System.err.println("Couldn't read stream from file: " + path); 
       return null; 
      } 
      if (count <= 0) { 
       System.err.println("Empty file: " + path); 
       return null; 
      } 
      return new ImageIcon(Toolkit.getDefaultToolkit().createImage(buf)); 
     } else { 
      System.err.println("Couldn't find file: " + path); 
      return null; 
     } 
    } 

我這樣稱呼它

loadImage("share_back_img_1_512", "jpg"); 

我的問題是:如何使它更具活力。

目前我正在測試一些圖像,但我有像最終的小程序100圖像的東西。

我不得不將圖像存儲在一個包中以便能夠訪問它們。

所以這裏的問題是:

有沒有一種方法取決於包的內容載入圖像? 獲取名稱,大小,擴展名...?

基本上是一個簡單的生成ImageIcons

回答

1

你寫你流讀取的方式的方式 - 它可能會導致部分讀取,因爲只需一個電話讀不保證返回所有字節表示該流可能最終產生。

嘗試阿帕奇百科全書IOUtils#toByteArray(InputStream的),或者包括自己的簡單實用的方法:

public static final byte[] readBytes(final InputStream is) throws IOException { 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(Short.MAX_VALUE); 
    byte[] b = new byte[Short.MAX_VALUE]; 
    int len = 0; 
    while ((len = is.read(b)) != -1) { 
     baos.write(b, 0, len); 
    } 
    return baos.toByteArray(); 
} 

至於你的組織的關注...還有就是得到一個「目錄沒有簡單+可靠的方法列出「一個包的內容。可以跨多個類路徑條目定義包,跨越JAR和文件夾甚至網絡資源。

如果有問題的包都包含一個JAR中,你可以考慮考慮像這裏所描述的那樣:http://www.rgagnon.com/javadetails/java-0513.html

更可靠和更便攜的方式可能是維護一個包含列表的文本文件要加載的圖像。加載列表作爲資源,然後使用列表循環並加載文本文件中列出的所有圖像。