Tetramputechture
Tetramputechture

Reputation: 2921

OpenGL (LWJGL) - Get Pixel Color of Texture

How do I go about getting the pixel color of an RGBA texture? Say I have a function like this:

public Color getPixel(int x, int y) {
    int r = ...
    int g = ...
    int b = ...
    int a = ...

    return new Color(r, g, b, a);
}

I'm having a hard time using glGetTexImage() to work;

    int[] p = new int[size.x * size.y * 4];
    ByteBuffer buffer = ByteBuffer.allocateDirect(size.x * size.y * 16);
    glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
    buffer.asIntBuffer().get(p);

    for (int i = 0; i < p.length; i++) {
        p[i] = (int) (p[i] & 0xFF);
    }

But I don't know how to access a pixel with a given coordinate.

Upvotes: 1

Views: 3793

Answers (2)

Tetramputechture
Tetramputechture

Reputation: 2921

Here's what I did to accomplish this.

First, I set the pixels in a byte[] with glGetTexImage.

byte[] pixels = new byte[size.x * size.y * 4];
ByteBuffer buffer = ByteBuffer.allocateDirect(pixels.length);
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
buffer.get(pixels);

Then, to get a pixel at a specific coordinate, here's the algorithm I used:

public Color getPixel(int x, int y) {
    if (x > size.x || y > size.y) {
        return null;
    }

    int index = (x + y * size.x) * 4;

    int r = pixels[index] & 0xFF;
    int g = pixels[index + 1] & 0xFF;
    int b = pixels[index + 2] & 0xFF;
    int a = pixels[index + 3] & 0xFF;

    return new Color(r, g, b, a);
}

This returns a Color object with arguments ranging from 0-255, as expected.

Upvotes: 0

jak89 _1
jak89 _1

Reputation: 25

like this? hope this helps you :)

public Color getPixel(BufferedImage image, int x, int y) {
    ByteBuffer buffer = BufferUtils.createByteBuffer(image.getWidth() *
      image.getHeight() * 4); //4 for RGBA, 3 for RGB

    if (y <= image.getHeight() && x <= image.getWidth()){
      int pixel = pixels[y * image.getWidth() + x];
      int r=(pixel >> 16) & 0xFF);     // Red 
      int g=(pixel >> 8) & 0xFF);      // Green 
      int b=(pixel & 0xFF);            // Blue
      int a=(pixel >> 24) & 0xFF);     // Alpha
      return new Color(r,g,b,a)
    }
    else{
      return new Color(0,0,0,1);
    }
}

its not testet but should work

Upvotes: 1

Related Questions