0

Hey I would like to know if there is a way to only take part of an image and turn it into a texture for LWJGL. Here is my basic code for loading an image and using as a texture. The PNG decoder is from the twl library. Thanks in advance for the help.

int floorTexture = glGenTextures();
        {
            InputStream in = null;
            try {
                in = new FileInputStream("res/floor.png");
                PNGdecoder decoder = new PNGdecoder(in);
                ByteBuffer buffer = BufferUtils.createByteBuffer(4 * decoder.getWidth() * decoder.getHeight());
                decoder.decode(buffer, decoder.getWidth() * 4, Format.RGBA);
                buffer.flip();
                in.close();
                glBindTexture(GL_TEXTURE_2D, floorTexture);
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
                glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, decoder.getWidth(), decoder.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
                glBindTexture(GL_TEXTURE_2D, 0);
            } catch (FileNotFoundException ex) {
                System.err.println("Failed to find the texture files.");
                Display.destroy();
                System.exit(1);
            } catch (IOException ex) {
                System.err.println("Failed to load the texture files.");
                Display.destroy();
                System.exit(1);
            }
        }
me me
  • 778
  • 2
  • 7
  • 18

1 Answers1

1

You can decode the PNG to a BufferedImage, then use getRGB() to extract the data for the region you are interested in. You may need some additional code to convert the (A)RGB ints to a byte buffer format accepted by GL. For a more detailed example of doing this look at the answer to this question LWJGL Textures and Strings.

However, instead of this, in GL you typically use texture coordinates to select the right subimage for what you are rendering.

The advantage of this method is that you can use a single glDrawElements/glDrawArrays call to render polygons with different textures, improving rendering performance.

Community
  • 1
  • 1
Stefan Haustein
  • 18,427
  • 3
  • 36
  • 51