Stefan
Stefan

Reputation: 33

Get pixel's color in C++, Linux

I'm looking for a possibility to get the color of a pixel with given screen coordinates (x,y) in c++ / Linux? Maybe something similarly like getPixel() in Windows. I spent the whole day to find sth but without any success.

Thanks, Stefan

Upvotes: 3

Views: 6512

Answers (3)

Josh Albert
Josh Albert

Reputation: 1124

I have come across this same issue and have found the solution to be dependant on the situation at hand. A great way to go about doing it is to capture a bitmap of the window you are looking at. Then have a function search for the pixel in there that you are looking for. Keep in mind the x,y coords will start from the windows upper left corner as apposed to the screen's upper left. As to how to do this, I suggest you take a look at SCAR Divi witten by Freddy1990 http://freddy1990.com/ and Simba http://villavu.com/.

Those programs are used to program automated tasks on the computer and use pixel colour finding to achieve some tasks. Simba is open source and still in its infant stages. It uses pascal. However you could use the library it uses as an extention from C and sacrifice a little speed.

Upvotes: 0

baol
baol

Reputation: 4358

Assuming you mean using C and GTK the answer can be using:

gdk_get_default_root_window()

And

GdkPixbuf*  gdk_pixbuf_get_from_drawable    (GdkPixbuf *dest,
                                             GdkDrawable *src,
                                             GdkColormap *cmap,
                                             int src_x,
                                             int src_y,
                                             int dest_x,
                                             int dest_y,
                                             int width,
                                             int height);

EDIT: sample c++ code using Gdkmm (note that this is just a sample that assume an RGB color space, you should check the colorspace of the drawable before giving a meaning to the raw bytes).

#include <iostream>
#include <gtkmm.h>
#include <gdkmm.h>

int main(int argc, char* argv[])
{
  Gtk::Main kit(argc, argv);
  if(argc != 3) { std::cerr << argv[0] << " x y" << std::endl; return 1;}
  int x = atoi(argv[1]);
  int y = atoi(argv[2]);
  Glib::RefPtr<Gdk::Screen> screen = Gdk::Screen::get_default();
  Glib::RefPtr<Gdk::Drawable> win = screen->get_root_window();
  Glib::RefPtr<Gdk::Pixbuf> pb = Gdk::Pixbuf::create(win, x, y, 1, 1);
  unsigned char* rgb = pb->get_pixels();
  std::cerr << (int)rgb[0] << ", " << (int)rgb[1] << ", " << (int)rgb[2] << std::endl;
  return 0;
}

Upvotes: 3

Ken Bloom
Ken Bloom

Reputation: 58800

See various different techniques posted at http://ubuntuforums.org/showthread.php?t=715256

Upvotes: 0

Related Questions