Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ...package declairation
- import java.awt.image.BufferedImage;
- import java.io.File;
- import java.io.IOException;
- import java.nio.ByteBuffer;
- import javax.imageio.ImageIO;
- import org.lwjgl.BufferUtils;
- import org.lwjgl.opengl.GL11;
- import org.lwjgl.opengl.GL12;
- import org.lwjgl.opengl.GL13;
- public class Texture {
- public BufferedImage source;
- public int id;
- public Texture(){
- id = GL11.glGenTextures();
- }
- public void bind(){
- GL11.glBindTexture(GL11.GL_TEXTURE_2D, id);
- }
- public void unbind(){
- GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
- }
- public int getID(){
- return id;
- }
- public void dispose() {
- GL11.glDeleteTextures(id);
- }
- public static Texture loadTexture(String resourceName){
- Texture texture = new Texture();
- BufferedImage image = null;
- try {
- image = ImageIO.read(new File(resourceName));
- } catch (IOException e) {
- e.printStackTrace();
- }
- 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() * 4); // 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));
- buffer.put((byte) ((pixel >> 8) & 0xFF));
- buffer.put((byte) (pixel & 0xFF));
- buffer.put((byte) ((pixel >> 24) & 0xFF));
- }
- }
- buffer.flip();
- texture.id = GL11.glGenTextures();
- texture.bind();
- // Setup wrap mode
- GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
- GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
- // Setup texture scaling filtering
- GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);
- GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
- // Send texel data to OpenGL
- GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, image.getWidth(), image.getHeight(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer);
- texture.unbind();
- return texture;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment