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

6
我有一个.NET BitmapSource对象。我想读取位图的四个角中的像素,并测试它们是否都比白色暗。我该怎么做?
编辑:我不介意将此对象转换为具有更好API的其他类型。
1个回答

11

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

2
你可以将bmp转换为所需的格式: if (bitmap.Format != PixelFormats.Bgra32) bitmap = new FormatConvertedBitmap(bitmap, PixelFormats.Bgra32, null, 0); - Eugene Maksimov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接