c# - 单击图片框时获取 PixelValue

标签 c# pixel picturebox

我正在处理一个 .NET C# 项目,我想在单击图片框时获取像素值,我该如何实现?

基本思想是当我点击图片框的任何地方时,我得到那个图像点的像素值..

谢谢!

最佳答案

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

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

希望对你有帮助

关于c# - 单击图片框时获取 PixelValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18210030/

相关文章:

c# - 日期时间变量 "tics"一小时

c# - 平滑滚动的垂直文本以获得进度

html - 屏幕分辨率和图像大小,如何正确

c# - 在 C# 中处理 OpenFileDialog?

C# 运行时应用程序诊断

c# - 如何创建继承自TextBox的类

python - 如何从图像中的对象大小(以像素为单位)根据英寸厘米等测量值来测量现实世界中的对象大小?

JavaScript 错误 : Cannot read property 'width' of null

C# 图片框.图像

c# - 将 PictureBox 与 LoadAsync 的 url 字符串绑定(bind)