Get PixelValue when click on a picturebox

爷,独闯天下 提交于 2019-12-21 18:33:39

问题


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!


回答1:


Use this:

private void pictureBox2_MouseUp(object sender, MouseEventArgs e)
{
    Bitmap b = new Bitmap(pictureBox1.Image);
    Color color = b.GetPixel(e.X, e.Y);
}



回答2:


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




回答3:


Unless that picturebox is in the size of a pixel, I don't think you can. Control onclick events doesn't save specific click location. If you are talking about color, not possible in c#



来源:https://stackoverflow.com/questions/18210030/get-pixelvalue-when-click-on-a-picturebox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!