Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get PixelValue when click on a picturebox

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!

like image 617
Matimont Avatar asked Feb 15 '23 14:02

Matimont


1 Answers

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

like image 175
Sriram Sakthivel Avatar answered Feb 23 '23 18:02

Sriram Sakthivel