Use unsafe in C # To speed up Image Processing

Source: Internet
Author: User

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 ));




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.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.