Color of a screen pixel

From Rosetta Code
Jump to: navigation, search
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.

Contents

[edit] App Inventor

App Inventor has two Canvas blocks to determine the color under a pixel.
GetBackgroundPixelColor returns a color from the Canvas but ignores Ball sprites and ImageSprites.
GetPixelColor returns a color from either the Canvas or a Ball sprite or ImageSprite.
In the app's display below, the purple Ball sprite was touched on the left canvas, but the pixel color (green) returned was from the area below it. <VIEW THE BLOCKS AND ANDROID APP DISPLAY>

[edit] Applesoft BASIC

Low-Resolution (Lo-Res) graphics 40x48, 16 colors, page 1

X =  PDL (0) * 5 / 32
Y = PDL (1) * 3 / 16
COLOR= SCRN( X,Y)

Hi-Resolution (Hi-Res) graphics 280x192, 6 colors

There is no HSCRN( X,Y) function in Applesoft. What follows is an elaborate subroutine that determines the hi-res color at the location given by variables X and Y on the current hi-res page. A color value in the range from 0 to 7 is returned in the variable C. The color is determined by peeking at adjacent pixels and the Most Significant Bit MSB. The VTAB routine is used as an aid to calculate the address of pixels. Other colors beyond the 6 hi-res colors can be displayed by positioning pixels at byte boundaries using the MSB. This routine is limited to the eight hi-res colors.

 
100 REM GET HCOLOR
110 REM PARAMETERS: X Y
120 REM RETURNS: C
130 REM
140 P = 0:X = X + 1
150 ON (X < 280) GOSUB 300
160 PR = P:P = 0:X = X - 2
170 ON (X > = 0) GOSUB 300
180 PL = P:X = X + 1: GOSUB 300
190 ODD = X - INT (X / 2) * 2
200 C = H * 4
210 IF NOT ((PL = PR) AND (PL < > P)) THEN C = C + P * 3: RETURN
220 IF ODD THEN P = NOT P
230 C = C + P + 1
240 RETURN
250 REM
260 REM GET PIXEL
270 REM PARAMETERS: X Y
280 REM RETURNS: H P
290 REM
300 H = INT (X / 7)
310 V = INT (Y / 8)
320 VO = PEEK (37)
330 HO = PEEK (36)
340 VTAB V + 1: HTAB 1
350 A = PEEK (41) * 256
360 A = A + PEEK (40) + H
370 VTAB VO + 1: HTAB HO + 1
380 A = A + 8192 - 1024
390 P = PEEK (230) / 32
400 IF P = 2 THEN A = A + 8192
410 A = A + (Y - V * 8) * 1024
420 B = X - H * 7
430 V = PEEK (A)
440 H = INT (V / 128)
450 V = INT (V / (2 ^ B))
460 P = V - INT (V / 2) * 2
470 RETURN
 
X = 267 : Y = 166 : GOSUB 100
HCOLOR= C
 

[edit] AutoHotkey

PixelGetColor, color, %X%, %Y%

[edit] AutoIt

$a = Mousegetpos()
PixelGetColor($a[0], $a[1])

[edit] BASIC

Works with: QuickBasic version 4.5

In a graphics mode (for instance, SCREEN 13 or SCREEN 12)

color = POINT(x, y)

[edit] BBC BASIC

In BBC BASIC for Windows you can read either the 'logical colour' (palette index) or the 'true colour' (24-bit RGB value).

      palette_index% = POINT(x%, y%)
RGB24b_colour% = TINT(x%, y%)

[edit] C

Library: Xlib
 
#include <X11/Xlib.h>
void
get_pixel_color (Display *d, int x, int y, XColor *color)
{
XImage *image;
image = XGetImage (d, RootWindow (d, DefaultScreen (d)), x, y, 1, 1, AllPlanes, XYPixmap);
color->pixel = XGetPixel (image, 0, 0);
XFree (image);
XQueryColor (d, DefaultColormap(d, DefaultScreen (d)), color);
}
 
// Your code
XColor c;
get_pixel_color (display, 30, 40, &c);
printf ("%d %d %d\n", c.red, c.green, c.blue);
 
Works with: Windows

(Linux users, see grabc.)

#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;
}

[edit] C#

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));
}
}

Sample output:

Color [A=255, R=243, G=242, B=231]

[edit] Clojure

(defn get-color-at [x y]
(.getPixelColor (java.awt.Robot.) x y))

[edit] Common Lisp

Using Allegro and their Common Graphics package

(in-package :cg-user)
 
(defun print-hex (n)
(let ((*print-base* 16.) (*print-radix* t))
(print n)) t)
 
(defun get-byte (n byte)
(logand (ash n (* byte -8)) #xFF))
 
(defun get-pixel (x y)
(let ((pixval (caar (contents (get-screen-pixmap :box (make-box x y (+ x 1) (+ y 1)))))))
(mapcar #'(lambda (i) (get-byte pixval i)) '(2 1 0 3))))
 
(defun get-mouse-pixel ()
(let ((pos (cursor-position (screen *system*))))
(get-pixel (position-x pos) (position-y pos))))
 
(print-hex (get-mouse-pixel))

Sample output: (values are in RGBA order):

(#xe0 #x43 #x43 #xff)

[edit] Delphi

 
program ScreenPixel;
 
{$APPTYPE CONSOLE}
 
uses
Windows,
SysUtils,
Graphics;
 
 
// Use this function in a GUI application to return the color
function GetPixelColourAsColor(const PixelCoords: TPoint): TColor;
var
dc: HDC;
begin
// Get Device Context of windows desktop
dc := GetDC(0);
// Read the color of the pixel at the given coordinates
Result := GetPixel(dc,PixelCoords.X,PixelCoords.Y);
end;
 
// Use this function to get a string representation of the current colour
function GetPixelColourAsString(const PixelCoords: TPoint): string;
var
r,g,b: Byte;
col: TColor;
begin
col := GetPixelColourAsColor(PixelCoords);
 
// Convert the Delphi TColor value to it's RGB components
r := col and $FF;
g := (col shr 8) and $FF;
b := (col shr 16) and $FF;
 
// Format the result
Result := 'R('+IntToStr(r)+') G('+IntToStr(g)+') G('+IntToStr(b)+')';
 
{
Alternatively, format the result as follows to get a
string representation of the Delphi TColor value
 
Result := ColorToString(GetPixel(dc,curP.X,curP.Y));
}

 
end;
 
var
s: string;
P: TPoint;
begin
s := '';
 
Writeln('Move mouse over a pixel. Hit return to get colour of selected pixel.');
 
repeat
Readln(s);
if s = '' then
begin
GetCursorPos(P);
Writeln('Colour at cursor position X:'+
IntToStr(P.X)+' Y:'+
IntToStr(P.Y) +' = '+
GetPixelColourAsString(P)
);
Writeln('');
Writeln('Move mouse and hit enter again.');
end;
until
SameText(s,'quit');
 
end.
 

Example output:

Move mouse over a pixel. Hit return to get colour of selected pixel.

Colour at cursor position X:429 Y:161 = R(0) G(0) B(0)

Move mouse and hit enter again.

Colour at cursor position X:942 Y:358 = R(182) G(206) B(231)

Move mouse and hit enter again.

Colour at cursor position X:704 Y:103 = R(240) G(240) B(240)

Move mouse and hit enter again.

Colour at cursor position X:2756 Y:59 = R(250) G(196) B(182)

[edit] F#

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

[edit] C++/CLI

 
using namespace System;
using namespace System::Drawing;
using namespace System::Windows::Forms;
 
[STAThreadAttribute]
int main()
{
Point^ MousePoint = gcnew Point();
Control^ TempControl = gcnew Control();
MousePoint = TempControl->MousePosition;
Bitmap^ TempBitmap = gcnew Bitmap(1,1);
Graphics^ g = Graphics::FromImage(TempBitmap);
g->CopyFromScreen((Point)MousePoint, Point(0, 0), Size(1, 1));
Color color = TempBitmap->GetPixel(0,0);
Console::WriteLine("R: "+color.R.ToString());
Console::WriteLine("G: "+color.G.ToString());
Console::WriteLine("B: "+color.B.ToString());
}
 

[edit] Integer BASIC

See Applesoft BASIC.

[edit] Icon and Unicon

Icon and Unicon don't have direct access to the screen; however, we can read the colour of of a maximal sized window instead. The graphics procedure generates all pixels from a rectangular selection as a comma separated string with RGB values.

link graphics,printf
 
procedure main()
 
WOpen("canvas=hidden") # hide for query
height := WAttrib("displayheight") - 45 # adjust for ...
width := WAttrib("displaywidth") - 20 # ... window 7 borders
WClose(&window)
 
W := WOpen("size="||width||","||height,"bg=black") |
stop("Unable to open window")
 
every 1 to 10 do { # generate some random rectangles within the frame
x := ?width
y := ?(height-100)
WAttrib("fg="||?["red","green","blue","purple","yellow"])
FillRectangle(x,x+50,y,y+50)
}
 
while Event() do
printf("x=%d,y=%d pixel=%s\n",&x,&y,Pixel(&x,&y,&x,&y))
 
WDone(W) # q to exit
end
 

graphics.icn provides graphics printf.icn provides printf

Sample Output:
x=943,y=946 pixel=0,0,65535
x=658,y=610 pixel=47802,0,65535
x=934,y=487 pixel=0,0,0

[edit] Java

Uses: Robot
public static Color getColorAt(int x, int y){
return new Robot().getPixelColor(x, y);
}

[edit] Liberty BASIC

'This example 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

[edit] Locomotive Basic

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

[edit]

CLEARSCREEN
SHOW PIXEL
[255 255 255]

[edit] Nimrod

Library: GTK2
import gtk2, gdk2, gdk2pixbuf
gtk2.nimrod_init()
 
proc getPixelColor(x, y: int32): auto =
var p = pixbufNew(COLORSPACE_RGB, false, 8, 1, 1)
discard p.getFromDrawable(getDefaultRootWindow().drawable,
getDefaultScreen().getSystemColormap(), x, y, 0, 0, 1, 1)
result = cast[tuple[r, g, b: uint8]](p.getPixels[])
 
echo getPixelColor(0, 0)

[edit] PHP

Works with: PHP version 5.2.2
Works with: Windows
Library: GD
$img = imagegrabscreen();
$color = imagecolorat($im, 10, 50);
imagedestroy($im);

[edit] PicoLisp

Using 'grabc' as recommended in the C solution

(in '(grabc)
(mapcar hex (cdr (line NIL 1 2 2 2))) )

Output:

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

[edit] 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.

Color = Point(x, y)

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.

 
hDC = GetDC_(0)
Color = GetPixel_(hDC, x, y)
ReleaseDC_(0, hDC)

This work fine!!

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

[edit] Python

Library: PyWin32
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)
Library: PIL
Works with: Windows
only
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)
Library: PIL
Library: python-xlib
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)
Library: PyGTK
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)
Library: PyQt
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, i_x, i_y, 1, 1).toImage().pixel(0, 0)
i_colour = int(long_colour)
return ((i_colour >> 16) & 0xff), ((i_colour >> 8) & 0xff), (i_colour & 0xff)
 
print get_pixel_colour(0, 0)

[edit] Racket

See get-pixel-color.rkt.

[edit] Ruby

This example requires ImageMagick >= 6.2.10 (works on X11, unsure about other platforms).

module Screen
IMPORT_COMMAND = '/usr/bin/import'
 
# Returns an array with RGB values for the pixel at the given coords
def self.pixel(x, y)
if m = `#{IMPORT_COMMAND} -silent -window root -crop 1x1+#{x.to_i}+#{y.to_i} -depth 8 txt:-`.match(/\((\d+),(\d+),(\d+)\)/)
m[1..3].map(&:to_i)
else
false
end
end
end

[edit] Scala

Library: Scala
def getColorAt(x: Int, y: Int): Color = new Robot().getPixelColor(x, y)

[edit] Tcl

Library: Tk

Works only on X11 or OSX with Xquartz.

package require Tcl 8.5
package require Tk
 
# Farm out grabbing the screen to an external program.
# 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
}
# 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
}
 
# Demo...
puts [format "pixel at mouse: (%d,%d,%d)" \
{*}[getPixelAtPoint {*}[winfo pointerxy .]]]

[edit] TI-89 BASIC

Only the graph screen can be read.

pxlTest(y, x)              © returns boolean

[edit] Visual Basic .NET

  Private Function GetPixelColor(ByVal Location As Point) As Color
 
Dim b As New Bitmap(1, 1)
Dim g As Graphics = Graphics.FromImage(b)
 
g.CopyFromScreen(Location, Point.Empty, New Size(1, 1))
 
Return b.GetPixel(0, 0)
 
End Function

[edit] XPL0

Color gets either 1, 2, 4, 8, 15, 16, or 24 significant bits depending on the current graphic mode enabled on an IBM-PC compatible machine with VESA graphics.

code ReadPix=44;
int Color, X, Y;
Color:= ReadPix(X, Y);
Personal tools
Namespaces

Variants
Actions
Community
Explore
Misc
Toolbox