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

 
   
System.Drawing.Bitmap p_w_picpath = new System.Drawing.Bitmap(
Properties.Settings.Default.BackgroundPicture);
System.Drawing.Imaging.BitmapData data
= p_w_picpath.LockBits(
new System.Drawing.Rectangle( 0 , 0 , p_w_picpath.Width, p_w_picpath.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【项目属性】的【编译选项】里找到这个开关。