When adding skin function to Douban station yesterday, we need to traverse each pixel of the image and calculate the mean value. If the image is dark, the text turns white. If the image is bright, the text turns black. Computing directly in C # requires a certain performance cost (compared to unmanaged code). The larger the image size, the more serious the performance loss. Therefore, you should write this part of code into the unsafe statement so that it can be directly computed in the memory. The Code is as follows:
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 ));
}
}
Note that if the unsafe statement is used in the Code, the/unsafe parameter must be added during compilation, you can find this switch in compilation options of Visual Studio [project properties.