C# 单击picturebox时获取像素值

C# 单击picturebox时获取像素值,c#,pixel,picturebox,C#,Pixel,Picturebox,我正在从事一个.NET C#项目,希望在单击picturebox时获得像素值,我如何实现这一点 基本思想是,当我点击picturebox中的任意位置时,我会得到该图像点的像素值 谢谢 除非那个图片盒只有像素大小,否则我认为你不能。控件onclick事件不保存特定的单击位置。如果你说的是颜色,在c中是不可能的。使用这个: private void pictureBox2_MouseUp(object sender, MouseEventArgs e) { Bitmap b = new Bi

我正在从事一个.NET C#项目,希望在单击picturebox时获得像素值,我如何实现这一点

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


谢谢

除非那个图片盒只有像素大小,否则我认为你不能。控件onclick事件不保存特定的单击位置。如果你说的是颜色,在c中是不可能的。

使用这个:

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

正如@Hans指出的,
Bitmap.GetPixel
应该可以工作,除非您的
SizeMode
PictureBoxSizeMode.Normal或PictureBoxSizeMode.AutoSize
不同。为了让它一直工作,让我们访问名为
ImageRectangle
PictureBox
的私有属性

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
        }
    }
}

希望这有帮助

您是指单击点处的颜色吗?嗯,是的,颜色,可能还有该点处的字节值..我正在这样做:
private void panel\u click(object sender,EventArgs e){Image tempimage=(Image)img[0]。RenderImage(0);var bmp=新位图(tempimage);System.Drawing.Color myColor=bmp.GetPixel(MousePosition.X,MousePosition.Y);字符串hascode=myColor.GetHashCode().ToString();MessageBox.Show(hascode);}
您忘了检查PictureBox.SizeMode属性值。是的,我不知道那是什么。现在,.NET可以渲染16位图像吗?还是需要将其转换为24位bmp?我甚至找不到一种不先转换为24位bmp即可渲染16位图像的方法。。