In C# applications, the GetPixel
and SetPixel
methods are commonly used to manipulate bitmaps. However, in some cases their performance can become a bottleneck. This article explores faster alternatives and evaluates potential performance improvements.
Customized DirectBitmap
classes provide direct access to bitmap data without intermediate locking and unlocking operations. This approach allows for faster pixel operations:
<code class="language-csharp">public class DirectBitmap : IDisposable { public Int32[] Bits { get; private set; } public int Width { get; private set; } public int Height { get; private set; } public void SetPixel(int x, int y, Color color) { Bits[x + (y * Width)] = color.ToArgb(); } public Color GetPixel(int x, int y) { int index = x + (y * Width); int col = Bits[index]; return Color.FromArgb(col); } }</code>
DirectBitmap
class implements IDisposable
to facilitate the management of memory resources. The following table compares the performance of the direct bitmap method with the LockBits
and SetPixel
methods:
方法 | 4x4 | 16x16 | 64x64 | 256x256 | 1024x1024 | 4096x4096 |
---|---|---|---|---|---|---|
DirectBitmap | 2 | 28 | 668 | 8219 | 178639 | |
LockBits | 2 | 3 | 33 | 670 | 9612 | 197115 |
SetPixel | 45 | 371 | 5920 | 97477 | 1563171 | 25811013 |
As can be seen from the table, the DirectBitmap
class significantly outperforms SetPixel
in performance, especially when dealing with larger bitmaps.
For pixel manipulation in bitmap processing applications, using a custom DirectBitmap
class can significantly improve performance. This approach enables faster processing by eliminating locking and unlocking operations and providing direct access to bitmap data.
The above is the detailed content of How Can I Speed Up Bitmap Pixel Manipulation in C# Beyond GetPixel and SetPixel?. For more information, please follow other related articles on the PHP Chinese website!