Color of a screen pixel: Difference between revisions

From Rosetta Code
(No difference)

Revision as of 13:27, 6 February 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.

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#

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

Bitmap img = new Bitmap(1, 1); Graphics g = Graphics.FromImage(img); g.CopyFromScreen(new Point(x, y), new Point(0, 0), new Size(1, 1));

Color color = img.GetPixel(x, y);</lang>

F#

The C# example copies the entire screen into our private bitmap but that's unnecessary. All we need is the single pixel. Also, it doesn't appear that the bitmap and graphics object are being disposed of there. Other than that, this is essentially identical to that solution. <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>

Java

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

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

}</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>

Python

<lang python> from PIL import ImageGrab pixels = ImageGrab.grab().load() print pixels[0,0] </lang>