2017-07-18 49 views
0

我跟着一本關於LWJGL3的教程書,我試圖讓自己的圖片加載代碼(本書代碼不使用STB庫),它在工程中工作得很好正常運行(IntelliJ IDE,直接從build文件夾中運行),它將圖像從ByteBuffer中加載並且stbi_load_from_memory工作正常,但只要它被編譯並放入jar文件中就會停止工作,即使圖像已成功加載到ByteBuffer中,就像stbi_load_from_memory函數在Jar中返回null一樣。LWJGL 3 stbi_load_from_memory在jar中不工作

代碼:

public static ByteBuffer loadImage(String fileName, IntBuffer w, 
    IntBuffer h, IntBuffer comp) throws Exception 
    { 
     ByteBuffer image; 
     //the class name is Utils 
     InputStream imageFile = 
     Utils.class.getResourceAsStream(fileName); 

     //The image data gets put into the byte array no matter if 
     //its a jar or not 
     byte[] imageData = new byte[imageFile.available()]; 
     imageFile.read(imageData); 
     ByteBuffer imageBuffer = 
     BufferUtils.createByteBuffer(imageData.length); 
     imageBuffer.put(imageData); 
     imageBuffer.flip(); 
     //imageBuffer is the right size and has the right contents    

     //This is where everything fails if its in a jar, 
     //image is set to null and the Exception is thrown 
     image = stbi_load_from_memory(imageBuffer, w, h, comp, 0); 

     if(image == null) 
     { 
      throw new Exception("Failed to load image: " + fileName); 
     } 

     return image; 
    } 

它不可能是一個拼寫錯誤的文件名或路徑求助,因爲它加載數據到數組正確不管它是一個罐子或沒有。

附加信息:

  • Java版本:1.8.0_131 64

  • 處理器硬件架構:

  • IDE版本(如果需要出於某種原因)的IntelliJ 2017年1月4日終極

  • 操作系統:Ubuntu 16.04 LTS 64位

  • 內核:Linux的4.8.0-58泛型AMD64

  • LWJGL版本:3.1.2

  • 該項目是由搖籃3.3

  • 如果需要的話,我會上傳和發佈整個源代碼的鏈接

回答

0

問題可能在你的imageFile.available()。 InputStream的available方法不是獲取流大小的好方法;實際上你不能得到流的大小,你必須閱讀它直到它結束。

你想要做的是將你的InputStream轉換爲字節數組。看看這裏如何做到這一點:link。 其餘的代碼應該沒問題。請注意,您需要一個直接的ByteBuffer,因此包裝字節數組將不起作用,但您已經使用了正確的方法(BufferUtils.createByteBuffer)。

如果你仍然有問題,看看從LWJGL這個例子:https://github.com/LWJGL/lwjgl3/blob/master/modules/core/src/test/java/org/lwjgl/demo/stb/Image.java#L43

+0

好耶發現問題再調試後,很顯然這該死的陣列終究不是相同的尺寸(不得不將其寫入到一個文件對於jar和非jar版本,並檢查大小和字節)。對不起,最近的回覆是在度假。謝了哥們。 – MCcomando