I'm working on a .NET C# project and would like to get the pixel value when I click a picturebox, how can I achieve that?
The basic idea is that when I click anywhere in the picturebox, I get the pixelvalue of that image point..
Thanks!
As @Hans pointed out Bitmap.GetPixel
should work unless you have different SizeMode
than PictureBoxSizeMode.Normal or PictureBoxSizeMode.AutoSize
. To make it work all the time let's access private property of PictureBox
named ImageRectangle
.
PropertyInfo imageRectangleProperty = typeof(PictureBox).GetProperty("ImageRectangle", BindingFlags.GetProperty | BindingFlags.NonPublic | BindingFlags.Instance);
private void pictureBox1_Click(object sender, EventArgs e)
{
if (pictureBox1.Image != null)
{
MouseEventArgs me = (MouseEventArgs)e;
Bitmap original = (Bitmap)pictureBox1.Image;
Color? color = null;
switch (pictureBox1.SizeMode)
{
case PictureBoxSizeMode.Normal:
case PictureBoxSizeMode.AutoSize:
{
color = original.GetPixel(me.X, me.Y);
break;
}
case PictureBoxSizeMode.CenterImage:
case PictureBoxSizeMode.StretchImage:
case PictureBoxSizeMode.Zoom:
{
Rectangle rectangle = (Rectangle)imageRectangleProperty.GetValue(pictureBox1, null);
if (rectangle.Contains(me.Location))
{
using (Bitmap copy = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.ClientSize.Height))
{
using (Graphics g = Graphics.FromImage(copy))
{
g.DrawImage(pictureBox1.Image, rectangle);
color = copy.GetPixel(me.X, me.Y);
}
}
}
break;
}
}
if (!color.HasValue)
{
//User clicked somewhere there is no image
}
else
{
//use color.Value
}
}
}
Hope this helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With