Skip to content

Instantly share code, notes, and snippets.

@audinue
Created July 20, 2023 09:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save audinue/ad53d354eccab217e5ec9c13cb34071d to your computer and use it in GitHub Desktop.
Save audinue/ad53d354eccab217e5ec9c13cb34071d to your computer and use it in GitHub Desktop.
public static int getInternalFormat(BufferedImage image) {
switch (image.getType()) {
case BufferedImage.TYPE_3BYTE_BGR:
return GL_RGB;
case BufferedImage.TYPE_4BYTE_ABGR:
return GL_RGBA;
default:
throw new UnsupportedOperationException();
}
}
public static int getFormat(BufferedImage image) {
switch (image.getType()) {
case BufferedImage.TYPE_3BYTE_BGR:
return GL_BGR;
case BufferedImage.TYPE_4BYTE_ABGR:
return GL_ABGR_EXT;
default:
throw new UnsupportedOperationException();
}
}
public static Texture loadTextureFromImage(BufferedImage image) {
int texture = glGenTextures();
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
byte[] array = ((DataBufferByte) image.getData().getDataBuffer()).getData();
ByteBuffer buffer = ByteBuffer.allocateDirect(array.length)
.order(ByteOrder.nativeOrder());
buffer.put(array)
.position(0);
glTexImage2D(
GL_TEXTURE_2D,
0,
getInternalFormat(image),
image.getWidth(),
image.getHeight(),
0,
getFormat(image),
GL_UNSIGNED_BYTE,
buffer);
glBindTexture(GL_TEXTURE_2D, 0);
return new Texture(texture, image.getWidth(), image.getHeight());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment