Hi~~
I want to add a texture on a plane with gl.glTexImage2D(…),but I dont understand how to change a image to byte array.Can anyone post this code.
Thank~
Firstly load the texture into a ByteBuffer
public void loadTexture()
{
BufferedImage buff=null;
int[] img = null;
try{
buff=ImageIO.read(new BufferedInputStream(this.getClass().getResourceAsStream("yourfilename")));
}catch(IOException ioex){System.out.println(ioex.toString());}
Raster r = buff.getRaster();
img = r.getPixels(0, 0, buff.getWidth(), buff.getHeight(), img);
texture = ByteBuffer.allocateDirect(buff.getWidth() * buff.getHeight() * 3);
for (int y = 0; y < buff.getHeight(); y++)
for (int x = 0; x < buff.getWidth(); x++)
{
texture.put((byte) img[(y * buff.getWidth() + x) * 3]);
texture.put((byte) img[(y * buff.getWidth() + x) * 3 + 1]);
texture.put((byte) img[(y * buff.getWidth() + x) * 3 + 2]);
}
tWidth = buff.getWidth();
tHeight = buff.getHeight();
}
And then use the teximage2D to actually link the buffer to a texture id number and set its parameters:
int textures[];
gl.glGenTextures(1,textures);
gl.glBindTexture(GL.GL_TEXTURE_2D, textures[0]);
loadTexture();
gl.glTexImage2D(GL.GL_TEXTURE_2D, 0, 3, tWidth, tHeight,0, GL.GL_RGB, GL.GL_UNSIGNED_BYTE, texture);
gl.glTexParameteri(GL.GL_TEXTURE_2D,GL.GL_TEXTURE_MIN_FILTER,GL.GL_LINEAR);
gl.glTexParameteri(GL.GL_TEXTURE_2D,GL.GL_TEXTURE_MAG_FILTER,GL.GL_LINEAR);
Hope this can help
thank a lot~~
what package you use~~eg ByteBuffer.
these code seem have problem~
[tr][td]
System.out.println(texture);
for (int y = 0; y < buff.getHeight(); y++){
for (int x = 0; x < buff.getWidth(); x++){
texture.put((byte) img[(y * buff.getWidth() + x) * 3]);
texture.put((byte) img[(y * buff.getWidth() + x) * 3 + 1]);
texture.put((byte) img[(y * buff.getWidth() + x) * 3 + 2]);
}
}[/td][/tr]
cant run…
um… why need *3
this code normally works perfectly fine for me.
maybe the problem comes from your line
system.out.println(texture);
that will crash if it even happen to compile
if you want to check texture you should do
system.out.println(texture.toString());
instead.
Concerning the reason of why * 3 i have no idea as i picked up the method in a tutorial ;D
*3 must be related to RGB on 8 bits don’t youi think?