Mattb2291
Mattb2291

Reputation: 167

C# convert stride/buffer/width/height to bitmap

I have an image width/height/stride and buffer.

How do I convert this information to a System.Drawing.Bitmap? Can I get the original image back if I have these 4 things?

Upvotes: 1

Views: 3178

Answers (2)

max
max

Reputation: 34407

There is a Bitmap constructor overload, which requires everything you have (plus PixelFormat):

public Bitmap(int width, int height, int stride, PixelFormat format, IntPtr scan0);

This might work (if args.Buffer is an array of blittable type, like byte for example):

Bitmap bitmap;
var gch = System.Runtime.InteropServices.GCHandle.Alloc(args.Buffer, GCHandleType.Pinned);
try
{
    bitmap = new Bitmap(
        args.Width, args.Height, args.Stride,
        System.Drawing.Imaging.PixelFormat.Format24bppRgb,
        gch.AddrOfPinnedObject());
}
finally
{
    gch.Free();
}

Update:

Probably it's better to copy image bytes to newly created Bitmap manually, because it seems like that constructors doesn't do that, and if byte[] array of image data gets garbage collected all sorts of bad things can happen.

var bitmap = new Bitmap(args.Width, args.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
var data = bitmap.LockBits(
    new Rectangle(0, 0, args.Width, args.Height),
    System.Drawing.Imaging.ImageLockMode.WriteOnly,
    System.Drawing.Imaging.PixelFormat.Format24bppRgb);

if(data.Stride == args.Stride)
{
    Marshal.Copy(args.Buffer, 0, data.Scan0, args.Stride * args.Height);
}
else
{
    int arrayOffset = 0;
    int imageOffset = 0;
    for(int y = 0; y < args.Height; ++y)
    {
        Marshal.Copy(args.Buffer, arrayOffset, (IntPtr)(((long)data.Scan0) + imageOffset), data.Stride);
        arrayOffset += args.Stride;
        imageOffset += data.Stride;
    }
}

bitmap.UnlockBits(data);

Upvotes: 1

codeteq
codeteq

Reputation: 1532

This should work if you have the buffer as byte[], a width and the height + the pixelformat (stride)

    public Bitmap CreateBitmapFromRawDataBuffer(int width, int height, PixelFormat imagePixelFormat, byte[] buffer)
    {
        Size imageSize = new Size(width, height);

        Bitmap bitmap = new Bitmap(imageSize.Width, imageSize.Height, imagePixelFormat);
        Rectangle wholeBitmap = new Rectangle(0, 0, bitmap.Width, bitmap.Height);

        // Lock all bitmap's pixels.
        BitmapData bitmapData = bitmap.LockBits(wholeBitmap, ImageLockMode.WriteOnly, imagePixelFormat);

        // Copy the buffer into bitmapData.
        System.Runtime.InteropServices.Marshal.Copy(buffer, 0, bitmapData.Scan0, buffer.Length);

        // Unlock  all bitmap's pixels.
        bitmap.UnlockBits(bitmapData);

        return bitmap;
    }

Upvotes: 1

Related Questions