在我的 C# (3.5) 应用程序中,我需要获取位图的红色、绿色和蓝色通道的平均颜色值。最好不使用外部库。这可以做到吗?如果是这样,怎么办?提前致谢。
尝试让事情变得更精确:位图中的每个像素都有一定的 RGB 颜色值。我想获取图像中所有像素的平均 RGB 值。
最快的方法是使用不安全的代码:
BitmapData srcData = bm.LockBits(
new Rectangle(0, 0, bm.Width, bm.Height),
ImageLockMode.ReadOnly,
PixelFormat.Format32bppArgb);
int stride = srcData.Stride;
IntPtr Scan0 = srcData.Scan0;
long[] totals = new long[] {0,0,0};
int width = bm.Width;
int height = bm.Height;
unsafe
{
byte* p = (byte*) (void*) Scan0;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
for (int color = 0; color < 3; color++)
{
int idx = (y*stride) + x*4 + color;
totals[color] += p[idx];
}
}
}
}
int avgB = totals[0] / (width*height);
int avgG = totals[1] / (width*height);
int avgR = totals[2] / (width*height);
注意:我没有测试这段代码...(我可能偷工减料)
此代码还假设一个 32 位图像。对于 24 位图像。改变x*4 to x*3
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)