Color of a screen pixel: Difference between revisions

From Rosetta Code
Content added Content deleted
(→‎{{header|Java}}: Indicate where Robot comes from.)
Line 145: Line 145:
CallDLL #gdi32, "GetPixel", hDC As uLong, x As long, y As long, GetPixel As long
CallDLL #gdi32, "GetPixel", hDC As uLong, x As long, y As long, GetPixel As long
End Function</lang>
End Function</lang>

=={{header|Locomotive Basic}}==

<lang locobasic>10 x=320:y=200
20 color=TEST(x,y)
30 PRINT "Pen color at"; x; y; "is"; color</lang>


=={{header|Logo}}==
=={{header|Logo}}==

Revision as of 15:49, 30 December 2010

Task
Color of a screen pixel
You are encouraged to solve this task according to the task description, using any language you may know.

Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor. The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.

Applesoft BASIC

Low-Resolution (Lo-Res) graphics 40x48 16 colors, page 1 <lang Applesoft BASIC>X = PDL (0) * 5 / 32 Y = PDL (1) * 3 / 16

COLOR=  SCRN( X,Y)</lang>

AutoHotkey

<lang AutoHotkey>MouseGetPos, MouseX, MouseY PixelGetColor, color, %MouseX%, %MouseY%</lang>

BASIC

Works with: QuickBasic version 4.5

In a graphics mode (for instance, SCREEN 13 or SCREEN 12) <lang qbasic>color = point(x, y)</lang>

C

Works with: Windows

. It uses Windows API

(Linux users, see grabc.) <lang c>

  1. include <windows.h>

COLORREF getColorAtCursor(void) {

   POINT p;
   COLORREF color;
   HDC hDC;
   BOOL b;
   // Get the device context for the screen
   hDC = GetDC(NULL);
   if (hDC == NULL)
       return CLR_INVALID;
   // Get the current cursor position
   b = GetCursorPos(&p);
   if (!b)
       return CLR_INVALID;
   // Retrieve the color at that position
   color = GetPixel(hDC, p.x, p.y);
   // Release the device context again
   ReleaseDC(GetDesktopWindow(), hDC);
   return color;

}</lang>

C#

<lang csharp>using System; using System.Drawing; using System.Windows.Forms;

class Program {

   static Color GetPixel(Point position)
   {
       using (var bitmap = new Bitmap(1, 1))
       {
           using (var graphics = Graphics.FromImage(bitmap))
           {
               graphics.CopyFromScreen(position, new Point(0, 0), new Size(1, 1));
           }
           return bitmap.GetPixel(0, 0);
       }
   }
   static void Main()
   {
       Console.WriteLine(GetPixel(Cursor.Position));
   }

}</lang> Sample output: <lang>Color [A=255, R=243, G=242, B=231]</lang>

Clojure

<lang lisp>(defn get-color-at [x y]

 (.getPixelColor (java.awt.Robot.) x y))</lang>

F#

<lang fsharp>open System.Drawing open System.Windows.Forms

let GetPixel x y =

   use img = new Bitmap(1,1)
   use g = Graphics.FromImage(img)
   g.CopyFromScreen(new Point(x,y), new Point(0,0), new Size(1,1))
   let clr = img.GetPixel(0,0)
   (clr.R, clr.G, clr.B)

let GetPixelAtMouse () =

   let pt = Cursor.Position
   GetPixel pt.X pt.Y</lang>

C++/CLI

This example is incorrect. Please fix the code and remove this message.

Details: Does not identify library or platform dependencies

Pixel's color from cursor position: <lang cpp> POINT pt; pt.X=Cursor->Position.X; pt.Y=Cursor->Position.Y; Bitmap ^ myBitmap = gcnew Bitmap(1,1); Graphics ^ g = Graphics::FromImage(myBitmap); g->CopyFromScreen(pt, Drawing::Point(0, 0), Drawing::Size(1, 1)); Color color = myBitmap->GetPixel(0,0); this->Red->Text=color.R.ToString(); this->Blue->Text=color.B.ToString(); this->Green->Text=color.G.ToString(); </lang>

Java

Uses: java.awt

<lang java>public static Color getColorAt(int x, int y){

  return new Robot().getPixelColor(x, y);

}</lang>

Liberty BASIC

<lang lb>'This examples requires the Windows API Struct point, x As long, y As long

hDC = GetDC(0) result = GetCursorPos() Print GetPixel(hDC, point.x.struct, point.y.struct) Call ReleaseDC 0, hDC End


   Sub ReleaseDC hWnd, hDC
       CallDLL #user32,"ReleaseDC", hWnd As uLong, hDC As uLong, ret As Long
   End Sub
   Function GetDC(hWnd)
       CallDLL #user32, "GetDC", hWnd As uLong, GetDC As uLong
   End Function
   Function GetCursorPos()
       CallDLL #user32, "GetCursorPos", point As struct, GetCursorPos As uLong
   End Function
   Function GetPixel(hDC, x, y)
       CallDLL #gdi32, "GetPixel", hDC As uLong, x As long, y As long, GetPixel As long
   End Function</lang>

Locomotive Basic

<lang locobasic>10 x=320:y=200 20 color=TEST(x,y) 30 PRINT "Pen color at"; x; y; "is"; color</lang>

CLEARSCREEN
SHOW PIXEL
[255 255 255]

PicoLisp

Using 'grabc' as recommended in the C solution <lang PicoLisp>(in '(grabc)

  (mapcar hex (cdr (line NIL 1 2 2 2))) )</lang>

Output:

73,61,205
-> (73 61 205)

PureBasic

Return the color used at the x,y position in the current output. If the current output has an alpha channel then the result will be a 32bit RGBA value, otherwise it will be a 24bit RGB value. The color can be split in their RGB and alpha values by using the Red(), Green(), Blue() and Alpha() functions.

<lang PureBasic>Color = Point(x, y)</lang>

To get the colour of a pixel on the screen when it is not managed by PureBasic (ie. from other programs' windows), it is necessary to use Windows API. This works only under Windows. <lang PureBasic> hDC = GetDC_(0) Color = GetPixel_(hDC, x, y) ReleaseDC_(0, hDC)</lang>

This work fine!!

<lang PureBasic>poz.point If OpenWindow(0,0,0,100,45,"Get pixel color at cursor position",#PB_Window_MinimizeGadget)

 TextGadget(0,0,0,50,12,"Red: ")
 TextGadget(1,0,15,50,12,"Green: ")
 TextGadget(2,0,30,50,12,"Blue: ")
 TextGadget(3,50,0,50,12,"")
 TextGadget(4,50,15,50,12,"")
 TextGadget(5,50,30,50,12,"")
hDC = GetDC_(0)
Repeat
 oldx=poz\x
 oldy=poz\y

GetCursorPos_(@poz) Color = GetPixel_(hDC, poz\x, poz\y) If poz\x<>oldx Or poz\y<>oldy

 SetGadgetText(3,Str(Red(color)))
 SetGadgetText(4,Str(Green(color)))
 SetGadgetText(5,Str(Blue(color)))

EndIf event=WaitWindowEvent(200) Until event=#PB_Event_CloseWindow ReleaseDC_(0, hDC) EndIf</lang>

Python

Library: PyWin32

<lang python>def get_pixel_colour(i_x, i_y): import win32gui i_desktop_window_id = win32gui.GetDesktopWindow() i_desktop_window_dc = win32gui.GetWindowDC(i_desktop_window_id) long_colour = win32gui.GetPixel(i_desktop_window_dc, i_x, i_y) i_colour = int(long_colour) return (i_colour & 0xff), ((i_colour >> 8) & 0xff), ((i_colour >> 16) & 0xff)

print get_pixel_colour(0, 0)</lang>

Library: PIL
Works with: Windows

only

<lang python>def get_pixel_colour(i_x, i_y): import PIL.ImageGrab return PIL.ImageGrab.grab().load()[i_x, i_y]

print get_pixel_colour(0, 0)</lang>

Library: PIL
Library: python-xlib

<lang python>def get_pixel_colour(i_x, i_y): import PIL.Image # python-imaging import PIL.ImageStat # python-imaging import Xlib.display # python-xlib o_x_root = Xlib.display.Display().screen().root o_x_image = o_x_root.get_image(i_x, i_y, 1, 1, Xlib.X.ZPixmap, 0xffffffff) o_pil_image_rgb = PIL.Image.fromstring("RGB", (1, 1), o_x_image.data, "raw", "BGRX") lf_colour = PIL.ImageStat.Stat(o_pil_image_rgb).mean return tuple(map(int, lf_colour))

print get_pixel_colour(0, 0)</lang>

Library: PyGTK

<lang python>def get_pixel_colour(i_x, i_y): import gtk # python-gtk2 o_gdk_pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, 1, 1) o_gdk_pixbuf.get_from_drawable(gtk.gdk.get_default_root_window(), gtk.gdk.colormap_get_system(), i_x, i_y, 0, 0, 1, 1) return tuple(o_gdk_pixbuf.get_pixels_array().tolist()[0][0])

print get_pixel_colour(0, 0)</lang>

Library: PyQt

<lang python>def get_pixel_colour(i_x, i_y): import PyQt4.QtGui # python-qt4 app = PyQt4.QtGui.QApplication([]) long_qdesktop_id = PyQt4.QtGui.QApplication.desktop().winId() long_colour = PyQt4.QtGui.QPixmap.grabWindow(long_qdesktop_id).toImage().pixel(i_x, i_y) i_colour = int(long_colour) return ((i_colour >> 16) & 0xff), ((i_colour >> 8) & 0xff), (i_colour & 0xff)

print get_pixel_colour(0, 0)</lang>

Tcl

Library: Tk

Works only on X11 or OSX with Xquartz. <lang tcl>package require Tcl 8.5 package require Tk

  1. Farm out grabbing the screen to an external program.
  2. If it was just for a Tk window, we'd use the tkimg library instead

proc grabScreen {image} {

   set pipe [open {|xwd -root -silent | convert xwd:- ppm:-} rb]
   $image put [read $pipe]
   close $pipe

}

  1. Get the RGB data for a particular pixel (global coords)

proc getPixelAtPoint {x y} {

   set buffer [image create photo]
   grabScreen $buffer
   set data [$image get $x $y]
   image delete $buffer
   return $data

}

  1. Demo...

puts [format "pixel at mouse: (%d,%d,%d)" \

   {*}[getPixelAtPoint {*}[winfo pointerxy .]]]</lang>

TI-89 BASIC

Only the graph screen can be read.

<lang ti89b>pxlTest(y, x) © returns boolean</lang>