gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:20:01 25 4
gpt4 key购买 nike

我有一个 .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);

关于c# - 如何读取 BitmapSource 四个角的像素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14876989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com