我正在尝试为立方体加载纹理,但我使用的尺寸有问题。纹理具有二的幂(256x256)。当它应该使用 256 作为宽度和高度时,它会引发异常:
java.lang.IndexOutOfBoundsException: Required 262144 remaining bytes in buffer, only had 68998
at com.jogamp.common.nio.Buffers.rangeCheckBytes(Buffers.java:828)
编码:
private void initTexture(GL2ES2 gl) {
try {
BufferedImage bufferedImage = ImageIO.read(new URI("http://192.168.0.39/images/box.gif").toURL());
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "gif", byteArrayOutputStream);
byte[] imageData = byteArrayOutputStream.toByteArray();
imageBuffer = ByteBuffer.wrap(imageData);
} catch (Exception e) {
e.printStackTrace();
}
imageBuffer.rewind();
gl.glGenTextures(1, textureIds, 0);
gl.glBindTexture(GL2ES2.GL_TEXTURE_2D, textureIds[0]);
gl.glTexImage2D(GL2ES2.GL_TEXTURE_2D, 0, GL2ES2.GL_RGBA, 256, 256, 0, GL2ES2.GL_RGBA, GL2ES2.GL_UNSIGNED_BYTE, imageBuffer);
gl.glTexParameteri(GL2ES2.GL_TEXTURE_2D, GL2ES2.GL_TEXTURE_MAG_FILTER, GL2ES2.GL_LINEAR);
gl.glTexParameteri(GL2ES2.GL_TEXTURE_2D, GL2ES2.GL_TEXTURE_MIN_FILTER, GL2ES2.GL_LINEAR_MIPMAP_NEAREST);
gl.glGenerateMipmap(GL2ES2.GL_TEXTURE_2D);
gl.glBindTexture(GL2ES2.GL_TEXTURE_2D, 0);
}
当我将参数宽度/高度更改为 128 时,异常消失但立方体显示错误的颜色:
正如 bestsss 提到的,原因可能是某种原始格式。问题:我无法解决这个问题。我尝试了多种图像和格式。使用 gimp(在 ubuntu 上工作)创建它们,但例外总是相同的。所以我想原因是我以错误的方式阅读图像。一些想法?
更新
我的解决方案(使用 JOGL 类 TextureIO 和 Texture):
Texture texture;
private void initTexture(GL2ES2 gl) {
try {
texture = TextureIO.newTexture(new URI("http://192.168.0.39/images/box.gif").toURL(),true,null);
texture.setTexParameterf(GL2ES2.GL_TEXTURE_MIN_FILTER, GL2ES2.GL_LINEAR_MIPMAP_LINEAR);
texture.setTexParameterf(GL2ES2.GL_TEXTURE_MAG_FILTER, GL2ES2.GL_LINEAR);
} catch (Exception e) {
e.printStackTrace();
}
}
public void display(GL2ES2 gl) {
// code snipped
if (texture != null) {
texture.enable();
texture.bind();
}
// code snipped
}