如何读取BitmapSource四个角的像素?

我有一个.NET BitmapSource对象。 我想读取位图角落的四个像素,并测试它们是否都比白色更暗。 我怎样才能做到这一点?

编辑:我不介意将此对象转换为具有更好API的其他类型。

BitmapSource具有CopyPixels方法,可用于获取一个或多个像素值。

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

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);