I need to access each pixel of a Bitmap, work with them, then save them to a Bitmap.
Using Bitmap.GetPixel() and Bitmap.SetPixel(), my program runs slowly.
How can I quickly convert Bitmap to byte[] and back?
I need a byte[] with length = (4 * width * height), containing RGBA data of each pixel.
You can do it a couple of different ways. You can use
unsafeto get direct access to the data, or you can use marshaling to copy the data back and forth. The unsafe code is faster, but marshaling doesn’t require unsafe code. Here’s a performance comparison I did a while back.Here’s a complete sample using lockbits:
Here’s the same thing, but with marshaling: