Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何读取位图源四个角的像素?_C#_.net_Wpf_Bitmapsource - Fatal编程技术网

C# 如何读取位图源四个角的像素?

C# 如何读取位图源四个角的像素?,c#,.net,wpf,bitmapsource,C#,.net,Wpf,Bitmapsource,我有一个.NET对象。我想读取位图角落中的四个像素,并测试它们是否都比白色暗。我该怎么做 编辑:我不介意使用更好的API将此对象转换为另一种类型。BitmapSource有一种方法可用于获取一个或多个像素值 在给定像素坐标处获取单个像素值的辅助方法可能如下所示。请注意,它可能需要扩展以支持所有必需的像素格式 public static Color GetPixelColor(BitmapSource bitmap, int x, int y) { Color color; var

我有一个.NET对象。我想读取位图角落中的四个像素,并测试它们是否都比白色暗。我该怎么做

编辑:我不介意使用更好的API将此对象转换为另一种类型。

BitmapSource有一种方法可用于获取一个或多个像素值

在给定像素坐标处获取单个像素值的辅助方法可能如下所示。请注意,它可能需要扩展以支持所有必需的像素格式

public static Color GetPixelColor(BitmapSource bitmap, int x, int y)
{
    Color color;
    var bytesPerPixel = (bitmap.Format.BitsPerPixel + 7) / 8;
    var bytes = new byte[bytesPerPixel];
    var rect = new Int32Rect(x, y, 1, 1);

    bitmap.CopyPixels(rect, bytes, bytesPerPixel, 0);

    if (bitmap.Format == PixelFormats.Bgra32)
    {
        color = Color.FromArgb(bytes[3], bytes[2], bytes[1], bytes[0]);
    }
    else if (bitmap.Format == PixelFormats.Bgr32)
    {
        color = Color.FromRgb(bytes[2], bytes[1], bytes[0]);
    }
    // handle other required formats
    else
    {
        color = Colors.Black;
    }

    return color;
}
您可以使用如下方法:

var topLeftColor = GetPixelColor(bitmap, 0, 0);
var topRightColor = GetPixelColor(bitmap, bitmap.PixelWidth - 1, 0);
var bottomLeftColor = GetPixelColor(bitmap, 0, bitmap.PixelHeight - 1);
var bottomRightColor = GetPixelColor(bitmap, bitmap.PixelWidth - 1, bitmap.PixelHeight - 1);

您只需将bmp转换为所需格式:if(bitmap.format!=PixelFormats.Bgra32)bitmap=new FormatConvertedBitmap(bitmap,PixelFormats.Bgra32,null,0);