siva Rapolu
siva Rapolu

Reputation: 409

How to avoid the header data from a byte array of bitmap

I am trying to convert the bitmap image to byte array in C#. But as per the bitmap format first 12 bytes will be given to bitmap header.

// Converting the bitmap image data to byte array
 byte[] bitmapFileData = System.IO.File.ReadAllBytes(bitmapImageFilePath);

i debug this code, but it for my given monochorme bitmap image, the frist 56 bytes filled with some other data and from then its starting with (0, 0, 0, 255, 255,255,255,255......). Since its monochrome bitmap image the byte array contains the RGB of only (0,0,0,255 and 255,255,255,255).

Here my question is, how to filter the bitmap header from the byte array so that i can use the rest of the array as bitmap data. I know that offset value of bitmap format will explain. So which element of byte array gives the offset value?

Please excuse if its a basic question or discussed across different forums. I am new to the imaging part and did lot of googling, but not able to get the perfect understanding.

Can you please provide me the needed information.

Intention: 1. To convert the bitmap image to binary data 2. Get more understanding on image format stuff

Where i use: 1. To print the given bitmap image in one of the printers which will take the hexadecimal string or binary data of the image.

Upvotes: 0

Views: 4595

Answers (2)

Jim Mischel
Jim Mischel

Reputation: 134005

According to Bitmap Storage, the file contains a BITMAPFILEHEADER followed by a BITMAPINFOHEADER. The BITMAPFILEHEADER contains a field, bfOffBits that gives the offset of the first byte of bitmap data. So you should be able to read the file, locate the bfOffBits field, and use that to index into the array.

For example:

byte[] imageBytes = File.ReadAllBytes("filename.bmp");
int dataOffset = BitConverter.ToInt32(imageBytes, 10);
int firstPixelValue = imageBytes[dataOffset];

If you want to know how many pixels, you have to read the BITMAPINFOHEADER. You're probably better off getting the pinvoke signatures (see BITMAPFILEHEADER at pinvoke.net) and using a little unsafe code to set pointers to those structures so that they reference the values in the array.

Something like:

BITMAPFILEHEADER* bfh = (BITMAPFILEHEADER*)(&imageBytes[0]);
BITMAPINFOHEADER* bih = (BITMAPINFOHEADER*)(&imageBytes[14]);

That is, if you really want to work with the raw data rather than constructing a Bitmap object from the file.

Upvotes: 1

BigBadOwl
BigBadOwl

Reputation: 678

Why not open it as a bitmap and convert if from there?

using(Stream BitmapStream = System.IO.File.Open(fileName,System.IO.FileMode.Open ))
    {
         Image img = Image.FromStream(BitmapStream);

         mBitmap=new Bitmap(img);
         //...do whatever
    }

This post talks about converting images to byte arrays

Convert a bitmap into a byte array

Upvotes: 0

Related Questions