单击图片框时获取 PixelValue

Mat*_*ont 4 c# pixel picturebox

我正在开发一个 .NET C# 项目,并且希望在单击图片框时获取像素值,如何实现?

基本思想是,当我单击图片框中的任意位置时,我会得到该图像点的像素值。

谢谢!

Sri*_*vel 5

正如@Hans 指出的那样,除非你有不同的版本,否则Bitmap.GetPixel应该有效。为了使其始终有效,让我们访问named的私有属性。SizeModePictureBoxSizeMode.Normal or PictureBoxSizeMode.AutoSizePictureBoxImageRectangle

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助