昨天在给豆瓣电台加皮肤功能的时候考虑的,需要遍历图像的每个像素,然后算出均值。如果图片比较暗,那么文字就变成白色的,如果图片比较亮,文字就变成黑色的。直接在C#用计算这样的计算是需要付出一定性能代价的(相比非托管代码),而且图片越大,性能损耗就越严重。所以考虑把这部分代码写到unsafe语句中,让它在内存里直接计算。具体代码如下:

System.Drawing.Bitmap image = new System.Drawing.Bitmap(
Properties.Settings.Default.BackgroundPicture);
System.Drawing.Imaging.BitmapData data
= image.LockBits(
new System.Drawing.Rectangle(0, 0, image.Width, image.Height),
System.Drawing.Imaging.ImageLockMode.ReadWrite,
System.Drawing.Imaging.PixelFormat.Format24bppRgb);

unsafe
{
long r = 0;
long g = 0;
long b = 0;
long pixelCount = data.Height * data.Width;

byte* ptr = (byte*)(data.Scan0);
for (int i = 0; i < data.Height; i++)
{
for (int j = 0; j < data.Width; j++)
{
r
+= *ptr;
g
+= *(ptr + 1);
b
+= *(ptr + 2);
ptr
+= 3;
}
ptr
+= data.Stride - data.Width * 3;
}

double totalRGB = (r / pixelCount + g / pixelCount + b / pixelCount) / 3;
if(totalRGB > 127)
{
this.Foreground = new SolidColorBrush(Color.FromRgb(0, 0, 0));
}
else
{
this.Foreground = new SolidColorBrush(Color.FromRgb(255, 255, 255));
}
}

还有一点需要注意的是如果在代码里使用了unsafe语句,必须在编译的时候加上/unsafe参数,可以在Visual Studio【项目属性】的【编译选项】里找到这个开关。

PS。自己写的豆瓣电台终于是快要搞定了,有兴趣的朋友可以下载玩玩,Bug多多。地址:http://lemanz-douban-radio.googlecode.com/files/%E8%B1%86%E7%93%A3%E7%94%B5%E5%8F%B0%202%20RC2.zip

截图:

作者: 博比123 发表于 2011-05-28 01:03 原文链接

推荐.NET配套的通用数据层ORM框架:CYQ.Data 通用数据层框架