这是我第一次在OpenGL中使用纹理,尽管我已经研究了4个月了。当我尝试加载纹理(仅带有正方形的图像)时,我只会得到一个黑色正方形。\
我的纹理加载代码:
byte[] pixelData = new byte[0];
try {
BufferedImage bi = ImageIO.read(getClass().getResource(TEXTURE_FILES));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bi, "png", baos);
baos.flush();
pixelData = baos.toByteArray();
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
ByteBuffer byteBuffer = ByteBuffer.wrap(pixelData);
int texId = glGenTextures();
glBindTexture(GL_TEXTURE_2D, texId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_FALSE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, 500, 500, 0,
GL_RGB, GL_UNSIGNED_BYTE, byteBuffer);
return texId;
我尝试用一种更简单的方法加载纹理,但是没有用。我也尝试了另一张图像或将纹理不在我的jar文件中]
纹理显示代码:
glEnable(GL_TEXTURE_2D);
glColor4f(1f, 1f, 1f, 1f);
glBindTexture(GL_TEXTURE_2D, texId);
glBegin(GL_QUADS);
glTexCoord2f(0, 0);
glVertex2f(-1, -1);
glTexCoord2f(1, 0);
glVertex2f(1, -1);
glTexCoord2f(1, 1);
glVertex2f(1, 1);
glTexCoord2f(0, 1);
glVertex2f(-1, 1);
glEnd();
glDisable(GL_TEXTURE_2D);
我的opengl参数:
glEnable(GL_ALPHA_TEST);
glEnable(GL_DEPTH_TEST);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glEnable(GL_NORMALIZE);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glShadeModel(GL_SMOOTH);
glColorMask (true, true, true, true);
glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
我还从该论坛上阅读了许多其他技巧,但它们对我也没有用
我也尝试在具有不同视频卡的另一台计算机上运行它,但结果保持不变
可能是正在读取png文件:
BufferedImage bi = ImageIO.read(getClass().getResource(TEXTURE_FILES)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bi, "png", baos); baos.flush(); pixelData = baos.toByteArray(); baos.close();
我发现了一个cde代码段(LWJGL3 Texture),可以在其中循环读取文件:
InputStream is = getClass().getResourceAsStream(TEXTURE_FILES);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int read1 = is.read();
while (read1 != -1) {
baos.write(read1);
read1 = is.read();
}
byte[] pixelData= baos.toByteArray();
baos.close();
ByteBuffer byteBuffer = ByteBuffer.wrap(pixelData);
或者使用PNGDecoder
:(另请参见Load a PNG file with pure OpenGL和Loading PNG images with TWL's PNGDecoder)
InputStream in = getClass().getResourceAsStream(TEXTURE_FILES);
PNGDecoder decoder = new PNGDecoder(in);
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(3*decoder.getWidth()*decoder.getHeight());
decoder.decode(byteBuffer, decoder.getWidth()*3, PNGDecoder.Format.RGB);
byteBuffer.flip();