Author: conmajia
Link: http://topic.csdn.net/u/20120710/12/A6326F1D-D329-4268-9A04-76CFED772612.html
Getpixel and setpixel are often used when using the bitmap class, but these two methods are relatively slow, so lockbits/unlockbits are usually used to lock the bitmap in the memory to speed up the operation.
Private void lockunlockbitsexample (painteventargs e) {// create a new bitmap. create bitmap BMP = new Bitmap ("C: \ fakephoto.jpg"); // lock the bitmap's bits. lock bitmap rectangle rect = new rectangle (0, 0, BMP. width, BMP. height); system. drawing. imaging. bitmapdata bmp data = BMP. lockbits (rect, system. drawing. imaging. imagelockmode. readwrite, BMP. pixelformat); // get the address of the first line. get the first line address intptr = BMP data. scan0; // declare an array to hold the bytes of the bitmap. define an array to save bitmap int bytes = math. ABS (BMP data. stride) * BMP. height; byte [] rgbvalues = new byte [bytes]; // copy the RGB values into the array. copy the RGB value to the array system. runtime. interopservices. marshal. copy (PTR, rgbvalues, 0, bytes); // set every third value to 255. A 24bpp bitmap will look red. the bitmap with 3rd values per pixel set to BPP will become red for (INT counter = 2; counter <rgbvalues. length; counter + = 3) rgbvalues [Counter] = 255; // copy the RGB values back to the bitmap to copy the RGB value back to the bitmap system. runtime. interopservices. marshal. copy (rgbvalues, 0, PTR, bytes); // unlock the bits. unlock BMP. unlockbits (BMP data); // draw the modified image. draw the updated bitmap E. graphics. drawimage (BMP, 0,150 );}