Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Bitmap Object from raw bytes

Tags:

c#

bitmapimage

I am trying to create a bitmap object from raw bytes, my PixelFormat is RGB with 8 bits per sample, which is 3 bytes per pixel. now for this my stide will be 3 times the width.

But Bitmap class is always looking for multiplier of 4 for stride value. Please help me how to resolve this issues. if i give multiplier of 4 image is not coming properly.

Bitmap im = new Bitmap(MyOBJ.PixelData.Columns, MyOBJ.PixelData.Rows, (MyOBJ.PixelData.Columns*3),
System.Drawing.Imaging.PixelFormat.Format24bppRgb, Marshal.UnsafeAddrOfPinnedArrayElement(images[imageIndex], 0));
like image 742
user1935868 Avatar asked Dec 30 '12 16:12

user1935868


1 Answers

I've written a short sample which will pad every line of your array to adapt it to the required format. It will create a 2x2 check board bitmap.

byte[] bytes =
    {
        255, 255, 255,
        0, 0, 0,
        0, 0, 0,
        255, 255, 255,
    };
var columns = 2;
var rows = 2;
var stride = columns*4;
var newbytes = PadLines(bytes, rows, columns);
var im = new Bitmap(columns, rows, stride,
                    PixelFormat.Format24bppRgb, 
                    Marshal.UnsafeAddrOfPinnedArrayElement(newbytes, 0));

The PadLines method is written below. I tried to optimize it by using Buffer.BlockCopy in case your bitmaps are large.

static byte[] PadLines(byte[] bytes, int rows, int columns)
{
    //The old and new offsets could be passed through parameters,
    //but I hardcoded them here as a sample.
    var currentStride = columns*3;
    var newStride = columns*4;
    var newBytes = new byte[newStride*rows];
    for (var i = 0; i < rows; i++)
        Buffer.BlockCopy(bytes, currentStride*i, newBytes, newStride * i, currentStride);
    return newBytes;
}
like image 158
Mir Avatar answered Oct 15 '22 09:10

Mir