[C #] Fast Reading and Writing bitmap pixels

Source: Internet
Author: User

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

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: info-contact@alibabacloud.com 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.