Paul Grinberg
Paul Grinberg

Reputation: 1407

C# efficiently redraw Image with new data

What is the most memory efficient way to redraw an Image with new data in C#?

The external DLL I am using allocates a byte buffer to hold my (width * hight * bytesPerPixel) pixel data where each pixel is in ARGB32 format. The DLL automatically updates that buffer with new data by interacting with hardware, and then calls a C# callback saying that new data is ready to go. Right now, my scheme for displaying the new data is

var bmp = new Bitmap(_size.Width, _size.Height, PixelFormat.Format32bppArgb);
var bitmapData = bmp.LockBits(
                new Rectangle(new Point(0, 0), _size), 
                ImageLockMode.UserInputBuffer | ImageLockMode.WriteOnly,
                PixelFormat.Format32bppArgb, 
                unmanagedByteDataPtr);
bmp.UnlockBits(bitmapData);
myGui.ImageCtrl.Image = bmp;

This creates a new bitmap every time, which has a memory/performance penalty. Since my image size is not changing, is there a more efficient way to do this?

Upvotes: 1

Views: 403

Answers (1)

Luaan
Luaan

Reputation: 63732

You're using the wrong constructor. Just create a bitmap directly from the unmanaged data, and it will wrap the data, rather than creating a new bitmap just to throw it away immediately:

new Bitmap(_size.Width, _size.Height, 4 * _size.Width, PixelFormat.Format32bppArgb,
           unmanagedByteDataPtr);

Upvotes: 3

Related Questions