Casper Thule Hansen
Casper Thule Hansen

Reputation: 1550

Create bitmap from binary data

I have the following:

byte[] pixels = new byte[28] { 0x00, 0x00, 0x30, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x00, 0x00 };

This is an upside down exclamation mark like this:

0x00, 0x00,
0x30, 0x00,
0x30, 0x00,
0x00, 0x00,
0x00, 0x00,
0x30, 0x00,
0x30, 0x00,
0x30, 0x00,
0x30, 0x00,
0x30, 0x00,
0x30, 0x00,
0x30, 0x00,
0x30, 0x00,
0x00, 0x00

Which in binary is:

00000000    00000000
00110000    00000000
00110000    00000000
00000000    00000000
00000000    00000000
00110000    00000000
00110000    00000000
00110000    00000000
00110000    00000000
00110000    00000000
00110000    00000000
00110000    00000000
00110000    00000000
00000000    00000000

I need to convert this to a bitmap / create a bitmap. So the exclamation mark is white and the background is black. I need to be able to color the pixels also.

How to do this??

Upvotes: 2

Views: 8463

Answers (3)

L.B
L.B

Reputation: 116118

Assuming all your images are 16x14

Bitmap bmp = new Bitmap(16, 14);
int line=0;

for (int i = 0; i < pixels.Length; i++)
{
    for (int j = 0; j<8; j++)
    {
        if (((pixels[i] >> j) & 1) == 1)
        {
            bmp.SetPixel( (i%2)*8 + 7-j, line, Color.Black);
        }
    }
    if(i%2==1) line++;
}

Upvotes: 4

ken2k
ken2k

Reputation: 48985

From what I understand, you want to create a bitmap that looks similar to what's inside your byte array (your "exclamation mark").

You can create a bitmap from scratch, and using some loops, simply set pixels in your Bitmap. Here's a simple example that draws random white pixels on a black background. Adapt it to meet your requirements:

Bitmap zz = new Bitmap(100, 100);

using (Graphics g = Graphics.FromImage(zz))
{
    // Draws a black background
    g.Clear(Color.Black);
}

Random rnd = new Random();
for (int i = 0; i < zz.Height; i++)
{
    for (int j = 0; j < zz.Width; j++)
    {
        // Randomly add white pixels
        if (rnd.NextDouble() > 0.5)
        {
            zz.SetPixel(i, j, Color.White);
        }
    }
}

zz.Save(@"C:\myfile.bmp", ImageFormat.Bmp);

Upvotes: 0

kingpin
kingpin

Reputation: 1498

Consider reading Wikipedia about BMP format. You will need this to make sure that your array contains necessary meta data (e.g width and height). After making those changes you can use something like this

public static Bitmap ToBitmap(byte[] byteArray)
{
   using (var ms = new MemoryStream(byteArray))
   {
     var img = (Bitmap)Image.FromStream(ms);
     return img;
   }
}

Upvotes: 1

Related Questions