试图找到一种使用OpenGL在Java中渲染简单2D图像的方法我偶然发现了一个或多或少可理解的类,它为您完成了所有图像加载,我无法理解该怎么做。我相信它属于一个名叫Krythic的人,我认为它工作得很好,我甚至提出了它正在读取的图像的高度和宽度,看它是否能读出正确的图像。 但是这里仍然是上课(我不完全理解它是如何工作的):
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.ByteBuffer;
import javax.imageio.ImageIO;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL12;
import static org.lwjgl.opengl.GL11.*;
public class TextureLoader {
private static final int BYTES_PER_PIXEL = 4;//3 for RGB, 4 for RGBA
public static int loadTexture(BufferedImage image){
int[] pixels = new int[image.getWidth() * image.getHeight()];
image.getRGB(0, 0, image.getWidth(), image.getHeight(), pixels, 0, image.getWidth());
ByteBuffer buffer = BufferUtils.createByteBuffer(image.getWidth() * image.getHeight() * BYTES_PER_PIXEL); //4 for RGBA, 3 for RGB
for(int y = 0; y < image.getHeight(); y++){
for(int x = 0; x < image.getWidth(); x++){
int pixel = pixels[y * image.getWidth() + x];
buffer.put((byte) ((pixel >> 16) & 0xFF)); // Red component
buffer.put((byte) ((pixel >> 8) & 0xFF)); // Green component
buffer.put((byte) (pixel & 0xFF)); // Blue component
buffer.put((byte) ((pixel >> 24) & 0xFF)); // Alpha component. Only for RGBA
}
}
buffer.flip(); //FOR THE LOVE OF GOD DO NOT FORGET THIS
// You now have a ByteBuffer filled with the color data of each pixel.
// Now just create a texture ID and bind it. Then you can load it using
// whatever OpenGL method you want, for example:
int textureID = glGenTextures(); //Generate texture ID
glBindTexture(GL_TEXTURE_2D, textureID); //Bind texture ID
//Setup wrap mode
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
//Setup texture scaling filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
//Send texel data to OpenGL
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, image.getWidth(), image.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
//Return the texture ID so we can bind it later again
return textureID;
}
public static BufferedImage loadImage(String loc)
{
try {
return ImageIO.read(Main.class.getResource(loc));
} catch (IOException e) {
//Error Handling Here
}
return null;
}
以下是我写的代码,认为它会将图像呈现在四边形上,这可能就是问题所在。
while ( glfwWindowShouldClose(window) == GL_FALSE ) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
BufferedImage image = TextureLoader.loadImage("test.png");
int textureID = TextureLoader.loadTexture(image);
glBindTexture(GL_TEXTURE_2D, textureID);
glBegin(GL_QUADS);
glTexCoord2f(0, 0);
glVertex2f(-1f, -1f);
glTexCoord2f(1, 0);
glVertex2f( 0f, -1f);
glTexCoord2f(1, 1);
glVertex2f( 0f, 0f);
glTexCoord2f(0, 1);
glVertex2f(-1f, 0f);
glEnd();
glfwSwapBuffers(window);
glfwPollEvents();
}
因此它在屏幕的左下角绘制一个四边形,就像之前一样,但它是白色的,纹理应该是棕色的。它没有给我任何例外,所以我不确切地知道我搞砸了。
答案 0 :(得分:1)
使用
启用纹理glEnable(GL_TEXTURE_2D);