【问题标题】:LWJGL 3 stbi_load_from_memory not working when in jarLWJGL 3 stbi_load_from_memory 在 jar 中不工作
【发布时间】:2017-07-18 15:56:57
【问题描述】:

我正在跟随一本关于 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;
    }

不能是拼写错误的文件名或资源路径,因为无论是不是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 中制作的

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

【问题讨论】:

    标签: java intellij-idea lwjgl


    【解决方案1】:

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

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

    如果您仍然有问题,请查看 LWJGL 中的此示例:https://github.com/LWJGL/lwjgl3/blob/master/modules/samples/src/test/java/org/lwjgl/demo/stb/Image.java

    【讨论】:

    • 好的,是的,经过长时间的调试发现了问题,显然该死的数组毕竟大小不一样(必须将它写入 jar 和非 jar 版本的文件并检查大小和字节)。抱歉回复晚了,因为是放假。谢谢老兄。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多