LWJGL 3 stbi_load_from_memory 在 jar 中时不工作

LWJGL 3 stbi_load_from_memory not working when in jar

我正在阅读一本关于 LWJGL3 的教程书,我尝试编写自己的图像加载代码(本书代码不使用 STB 库)并且在项目 运行 时它工作得很好通常(IntelliJ IDE,运行 直接从构建文件夹),它将图像从 ByteBuffer 加载并且 stbi_load_from_memory 工作正常,但是一旦编译并放入 jar文件它只是停止工作,即使图像已成功加载到 ByteBuffer 中,就好像 stbi_load_from_memory 函数只是 returns null 如果它在 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;
    }

不能是拼写错误的文件名或资源路径,因为无论是不是jar,它都会正确地将数据加载到数组中。

附加信息:

问题可能出在您的 imageFile.available() 上。 InputStream 的 available 方法不是获取流大小的好方法;事实上你无法获取流的大小,你必须读取它直到它结束。

您要做的是将 InputStream 转换为字节数组。看看这里如何做到这一点:。 其余代码应该没问题。请注意,您需要一个直接的 ByteBuffer,因此包装字节数组将不起作用,但您已经使用了正确的方法 (BufferUtils.createByteBuffer)。

如果还有问题,请看LWJGL的这个例子:https://github.com/LWJGL/lwjgl3/blob/master/modules/samples/src/test/java/org/lwjgl/demo/stb/Image.java