Home >Backend Development >C++ >How Can I Efficiently Manipulate Bitmaps in C#?
Fast bitmap processing in C#
When working with large bitmaps, accessing and performing operations on a pixel-by-pixel basis may impact performance. C#'s built-in Bitmap.GetPixel()
and Bitmap.SetPixel()
methods are convenient but slow. This article explores alternative ways to quickly convert a bitmap to a byte array and back to a bitmap, allowing for efficient pixel operations.
Convert bitmap to byte array
Marshal.Copy()
method you can copy pixel data from a bitmap buffer into a byte array. Although marshaling does not require unsafe code, it may be slightly slower than the LockBits method. Convert byte array to bitmap
Marshal.Copy()
method to copy modified pixel data from a byte array back to a bitmap buffer. Performance comparison
LockBits method example
<code class="language-csharp">using System; using System.Drawing; using System.Runtime.InteropServices; public unsafe class FastBitmap { public static Image ThresholdUA(float thresh) { Bitmap b = new Bitmap(_image); BitmapData bData = b.LockBits(new Rectangle(0, 0, _image.Width, _image.Height), ImageLockMode.ReadWrite, b.PixelFormat); byte bitsPerPixel = GetBitsPerPixel(bData.PixelFormat); byte* scan0 = (byte*)bData.Scan0.ToPointer(); for (int i = 0; i < ... }</code>
Example of marshaling method
<code class="language-csharp">using System; using System.Drawing; using System.Runtime.InteropServices; public class FastBitmap { public static Image ThresholdMA(float thresh) { Bitmap b = new Bitmap(_image); BitmapData bData = b.LockBits(new Rectangle(0, 0, _image.Width, _image.Height), ImageLockMode.ReadWrite, b.PixelFormat); byte bitsPerPixel = GetBitsPerPixel(bData.PixelFormat); int size = bData.Stride * bData.Height; byte[] data = new byte[size]; Marshal.Copy(bData.Scan0, data, 0, size); for (int i = 0; i < ... }</code>
The above is the detailed content of How Can I Efficiently Manipulate Bitmaps in C#?. For more information, please follow other related articles on the PHP Chinese website!