-1

I am trying to read the RGB value of a screen pixel doing:

#include "stdafx.h"
#include<windows.h>
#include<stdio.h>
#include <gl\GL.h>

int main(int argc, char** argv)
{
    GLubyte color[3];
    glReadPixels(800, 800, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, &color);

    printf("R:%d G:%d B:%d", color[0], color[1], color[2]);

    while (1);

}

But it doesn't matter which coordinates I ask for. It always returns me R:204 G:204 B:204

What am I doing wrong?

sergio
  • 163
  • 1
  • 1
  • 11
  • 2
    What are you trying to do? You didn't even create an OpenGL context... – Pedro Boechat Jun 19 '17 at 15:40
  • I am trying to read the RGB value of the pixel in position x=800 y=800 – sergio Jun 19 '17 at 15:43
  • glReadPixels will only work in a screen that has an OpenGL context associated to it. In the glReadPixels docs there's a note: "Values for pixels that lie outside the window connected to the current GL context are undefined". In other words, you can only be sure you're going to get actual pixel values if you: 1. have a window and 2. connected a GL context to it. – Pedro Boechat Jun 19 '17 at 17:08

2 Answers2

1

glReadPixels() won't work without a current GL context. Though even if you did have a current context you can't read the system framebuffer that way.

genpfault
  • 47,669
  • 9
  • 68
  • 119
  • So, what would I do to read the RGB values of any pixel in screen efficiently? I need something faster than GetPixel method... – sergio Jun 19 '17 at 16:14
  • 3
    Did you read the answer to the question in the link? There they roughly explain why you can't use glReadPixels to take screenshots. If you're on windows you could try to use Win32. You can use CreateCompatibleBitmap with the screen device context as argument and copy the resulting bitmap to an in-memory bitmap, as described here: https://stackoverflow.com/questions/3291167/how-can-i-take-a-screenshot-in-a-windows-application – Pedro Boechat Jun 19 '17 at 17:01
0

As mentioned in the other answer and comments You can use glReadPixels only for pixels inside your OpenGL context window that are actually rendered at that time ... As you mentioned you have used GetPixel it hints you are using GDI. In that case you are trying to read GDI Canvas pixel from OpenGL which is not possible (the other way around is possible however but slow). So I advice to read this:

Where you can find example of both methods. If you are trying to obtain pixel from your own app then you can use different api then GetPixel.

If you're in VCL environment use Graphics::TBitmap::ScanLine property which can be used for direct pixel access without restrictions or performance hits if used properly.

On MSVC++ of GCC environment use WinAPI BitBlt but that is a bit slower and not as elegant (at least from my point of view).

Spektre
  • 41,942
  • 8
  • 91
  • 312