Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I load an image for use as an openGL texture with LWJGL?

Tags:

java

opengl

lwjgl

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!

like image 207
Bartvbl Avatar asked Mar 04 '11 13:03

Bartvbl


1 Answers

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;
}
like image 149
Ron Romero Avatar answered Sep 16 '22 17:09

Ron Romero