How to read pixels in four corners of a BitmapSource?

不问归期 提交于 2019-12-07 10:27:40

问题


I have a .NET BitmapSource object. I would like to read the four pixels in corners of the bitmap, and test whether all of them are darker than white. How can I do that?

Edit: I wouldn't mind converting this object to another type with a better API.


回答1:


BitmapSource has a CopyPixels method that can be used to get one or more pixel values.

A helper method that gets a single pixel value at a given pixel coordinate may look like shown below. Note that it perhaps has to be extended to support all required pixel formats.

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

You would use the method like this:

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


来源:https://stackoverflow.com/questions/14876989/how-to-read-pixels-in-four-corners-of-a-bitmapsource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!