This article analyzes the C# inverse color processing and its efficiency problems in examples. Share it for your reference. The specific analysis is as follows:
There are many information about this on the Internet, and the versions that you often see are as follows:
public Bitmap RePic(Bitmap thispic, int width, int height) { Bitmap bm = new Bitmap(width, height);//Initialize a recorded image objectint x, y, resultR, resultG, resultB; Color pixel; for (x = 0; x < width; x++) { for (y = 0; y < height; y++) { pixel = (x, y); //Get the pixel value of the current coordinateresultR = 255 - ; //Reverse RedresultG = 255 - ; //Anti-greenresultB = 255 - ; //Anti-blue(x, y, (resultR, resultG, resultB)); //Drawing} } return bm; //Return to the processed picture}
There is no problem with the above code execution, but there is a big problem with the efficiency, and it is very slow to execute. I tested the resolution of 1920 x 1080, and the execution time is about 8 seconds; the resolution of 2560 x 1920, and the execution time reaches about 15 seconds. Of course, small images are faster to process, and of course it is also related to the CPU configuration.
Later, I tried another method, using the BitmapData and LockBits methods in it, and the code was as follows:
public Bitmap reversePic(Bitmap thispic) { Bitmap src = new Bitmap((())); // Load the imageBitmapData srcdat = (new Rectangle(, ), , PixelFormat.Format24bppRgb); // Lock positioning mapunsafe // Unsafe code{ byte* pix = (byte*)srcdat.Scan0; // Pixel home addressfor (int i = 0; i < * ; i++) pix[i] = (byte)(255 - pix[i]); } (srcdat); // Unlockreturn src; }
The test efficiency has been significantly improved a lot, with a resolution of 2560 x 1920, and the execution time is less than 1 second. It seems that using pointers will be very efficient, but the operation of pointers in C# is considered unsafe. After using the unsafe keyword, there is a compilation error. The compiler option must be set to allow compilation of code using the unsafe keyword. The method is as follows:
Set this compiler option in the Visual Studio development environment
1. Open the Properties page of the project.
2. Click the Generate property page.
3. Select the "Allow unsafe code" check box.
I hope this article will be helpful to everyone's C# programming.