本文介绍了如何加载与LWJGL一起用作openGL纹理的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用LWJGL库将图像作为openGL的纹理加载.到目前为止,我需要将纹理作为ByteBuffer传递给openGL.我现在所拥有的是一些可以正确加载图像并将其存储在BufferedImage对象中的代码.问题是,我不知道如何从BufferedImage到包含以正确格式与openGL一起使用的数据(作为函数GL11.glTexImage2D()的输入)的ByteBuffer.非常感谢您的帮助!

I am trying to load an image as a texture for openGL using the LWJGL library. From what I found out so far, I need to pass the texture as a ByteBuffer to openGL. What I have right now is some code that correctly loads an image, and stores it in a BufferedImage object. The thing is, I have no clue how to get from a BufferedImage to a ByteBuffer that contains data in the right format for use with openGL (as input for the function GL11.glTexImage2D()).Help is greatly appreciated!

推荐答案

这是太空侵略者"示例中的一种方法,可以满足您的需求. (我认为)

Here's a method from the Space Invaders example that does what you want. (I think)

/**
 * Convert the buffered image to a texture
 */
private ByteBuffer convertImageData(BufferedImage bufferedImage) {
    ByteBuffer imageBuffer;
    WritableRaster raster;
    BufferedImage texImage;

    ColorModel glAlphaColorModel = new ComponentColorModel(ColorSpace
            .getInstance(ColorSpace.CS_sRGB), new int[] { 8, 8, 8, 8 },
            true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE);

    raster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE,
            bufferedImage.getWidth(), bufferedImage.getHeight(), 4, null);
    texImage = new BufferedImage(glAlphaColorModel, raster, true,
            new Hashtable());

    // copy the source image into the produced image
    Graphics g = texImage.getGraphics();
    g.setColor(new Color(0f, 0f, 0f, 0f));
    g.fillRect(0, 0, 256, 256);
    g.drawImage(bufferedImage, 0, 0, null);

    // build a byte buffer from the temporary image
    // that be used by OpenGL to produce a texture.
    byte[] data = ((DataBufferByte) texImage.getRaster().getDataBuffer())
            .getData();

    imageBuffer = ByteBuffer.allocateDirect(data.length);
    imageBuffer.order(ByteOrder.nativeOrder());
    imageBuffer.put(data, 0, data.length);
    imageBuffer.flip();

    return imageBuffer;
}

这篇关于如何加载与LWJGL一起用作openGL纹理的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 13:17