天天看點

使用BinCompiler将資源檔案打包成二進制檔案

在開發遊戲時,總是要使用很多的資源檔案,比如:圖檔、音樂等。而我們經常會遇到一些商業遊戲中都看不到這些資源檔案,那是因為商業遊戲,一般都會将這些資源檔案打包成二進制的檔案,然後在程式中讀取,并使用。這樣的遊戲看上去更顯得專業一些,本文我們就來學習一個最簡單的将資源檔案打包成二進制檔案的方法——使用BinCompiler将資源檔案打包成二進制檔案。

所需工具:BinCompiler(見附件)

運作“BinCompiler.exe”,指定要打包的資源檔案的路徑,和輸出二進制檔案的路徑,如下圖所示。

使用BinCompiler将資源檔案打包成二進制檔案
點選create按鈕,即在我們制定的位置産生一個bin檔案,當然在這個bin檔案所在目錄還會産生一個index.txt檔案。我們在程式中讀取這些資源時,需要使用這個index.txt。index.txt檔案如下所示:

  1. FName   Index   Pos Size     
  2. A_04.png    0   0   4141    
  3. A_03.png    1   4145    3802    
  4. A_02.png    2   7951    3813    
  5. A_01.png    3   11768   3959   

接下來我們可以使用BinReader.java檔案中的兩個方法來讀取這些資源檔案了。

代碼清單:BinReader.java

  1. /*******************************************************************************    
  2.  * Reads a file from the BIN file and return data as a byte buffer    
  3.  *******************************************************************************/    
  4. public byte[] readFile(String binfile, int pos)     
  5. {     
  6.     byte buffer[];     
  7.     int len;     
  8.     try {     
  9.         InputStream is = Class.getClass().getResourceAsStream("/" + binfile);     
  10.         is.skip(pos);     
  11.         len  = (is.read() & 0xFF) << 24;     
  12.         len  |= (is.read() 0xFF) << 16;     
  13.         len  |= (is.read() & 0xFF) << 8;     
  14.         len  |= (is.read() & 0xFF);     
  15.         buffer = new byte[len];     
  16.         is.read(buffer, 0, buffer.length);     
  17.         is.close();     
  18.         is = null;     
  19.         System.gc();     
  20.     } catch (Exception e) {     
  21.         buffer = null;     
  22.         e.printStackTrace();     
  23.         return null;     
  24.     }     
  25.     return buffer;     
  26. }     
  27.  * Reads a file from the BIN file and return data as an Image    
  28. public Image readImage(String binfile, long pos)     
  29.     long len;     
  30.         len  |= (is.read() &0xFF) << 16;     
  31.       len   -= 4;
  32.     return Image.createImage(buffer, 0, buffer.length);     
  33. }   

可以看出,這兩個方法都隻需要傳入bin檔案名和圖檔對應的pos,pos值就在我們上面所說的index.txt檔案中去找對應的就可以了。 

  1. Image image = readimage("images.bin", 0);