LWJGL 3 stbi_load_from_memory 在 jar 中时不工作

1 java intellij-idea lwjgl

我正在阅读一本关于 LWJGL3 的教程书,我尝试制作自己的图像加载代码(该书代码不使用 STB 库),当项目正常运行时(IntelliJ IDE,直接从build 文件夹),它将图像从 ByteBuffer 加载并stbi_load_from_memory工作正常,但是一旦编译并放入 jar 文件,它就停止工作,即使图像已成功加载到 ByteBuffer,就好像该stbi_load_from_memory函数只是如果它在 Jar 中,则返回 null。

代码:

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;
    }
Run Code Online (Sandbox Code Playgroud)

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

附加信息:

  • Java版本:1.8.0_131 64位

  • 处理器架构:amd64

  • IDE版本(如果出于某种原因需要):IntelliJ 2017.1.4 Ultimate

  • 操作系统:Ubuntu 16.04 LTS 64 位

  • 内核:Linux 4.8.0-58-generic amd64

  • LWJGL版本:3.1.2

  • 该项目是用Gradle 3.3制作的

  • 如果需要,我将上传并发布整个源代码的链接

小智 5

问题可能出在你的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。爪哇