Create bitmap from binary data

佐手、 提交于 2019-12-08 05:14:12

问题


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??


回答1:


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++;
}



回答2:


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;
   }
}



回答3:


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);


来源:https://stackoverflow.com/questions/9413701/create-bitmap-from-binary-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!