如何读取BitmapSource四个角的像素? [英] How to read pixels in four corners of a BitmapSource?

查看:89
本文介绍了如何读取BitmapSource四个角的像素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

我不介意将此对象转换为具有更好API的另一种类型.

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

推荐答案

BitmapSource具有

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

您将使用以下方法:

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

这篇关于如何读取BitmapSource四个角的像素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆