C# getting pixels in picturebox with cursor?

16,272

Solution 1

If you want to get the color of the clicked pixel:

Color pixelColor;

// add the mouse click event handler in designer mode or:
// myPicturebox.MouseClick += new MouseEventHandler(myPicturebox_MouseClick);
private void myPicturebox_MouseClick(object sender, MouseEventArgs e) {
   if (e.Button == MouseButtons.Left) 
      pixelColor = GetColorAt(e.Location);
}

private Color GetColorAt(Point point) {
   return ((Bitmap)myPicturebox.Image).GetPixel(point.X, point.Y);
}

Solution 2

The picture box has no way of getting the pixel. But the image it contains can be used to create a bitmap object that has a getpixel function. I would mention however that this is not the fastest of operations. If you need it to be quick I would look to the GDI win32 functions.

Share:
16,272
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    How can I get pixel x and y in a picturebox using the cursor?

  • Jason James
    Jason James about 8 years
    That's the way I had to do it as I been using the graphics object to draw on the picturebox. I render the complete image and then use GetPixel(x,y);
  • Christian Gold
    Christian Gold over 7 years
    Please keep in mind: the e.location is the location in the pictureBox whereas the real image is resized to fit into the box but still has its original size. When asking for the pixelvalue in this Image you get the value out of the unscaled image. This is (maybe) not the color value you might expect!