从字节数组创建PNG [英] Create a PNG from an array of bytes

查看:153
本文介绍了从字节数组创建PNG的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个一维字节数组,分别具有A,R,G和B的值,而且我知道期望图像的高度和宽度.如何编码这些数据并将其另存为PNG?

I have a 1 dimensional array of bytes, with separate values for A, R, G, and B, and I know the height and width of the expected image. How can I encode this data and save it as a PNG?

推荐答案

byte[] data = new byte[] {
    255, 255, 000, 000,  255, 255, 255, 255,  255, 255, 255, 255,  255, 255, 255, 255,  255, 255, 000, 000, 
    255, 255, 255, 255,  255, 255, 000, 000,  255, 255, 255, 255,  255, 255, 000, 000,  255, 255, 255, 255, 
    255, 255, 255, 255,  255, 255, 255, 255,  255, 255, 000, 000,  255, 255, 255, 255,  255, 255, 255, 255, 
    255, 255, 255, 255,  255, 255, 000, 000,  255, 255, 255, 255,  255, 255, 000, 000,  255, 255, 255, 255, 
    255, 255, 000, 000,  255, 255, 255, 255,  255, 255, 255, 255,  255, 255, 255, 255,  255, 255, 000, 000 
  };

  Bitmap bmp = new Bitmap(5, 5);
  for (int y = 0; y < 5; ++y)
    for (int x = 0; x < 5; ++x)
    {
      int offset = y * 5 * 4 + x * 4;
      bmp.SetPixel(x, y, Color.FromArgb(data[offset], data[offset + 1], data[offset + 2], data[offset + 3]));
    }
  bmp.Save(@"c:\tmp.png");
}


如果按以下方式对数组中的值进行排序:B G R A B G R A B G R A ...您可以使用以下代码,该代码应该更快:


If the values in your array are ordered this way: B G R A B G R A B G R A ... you could use the following code, which should be faster:

byte[] data = new byte[] {
  // B    G    R    A     B    G    R    A     B    G    R    A
      0,   0, 255, 255,    0,   0,   0, 255,    0, 255,   0, 255,
      0,   0,   0, 255,    0, 255,   0, 255,  255, 255, 255, 255,
      0, 255,   0, 255,    0,   0,   0, 255,  255,   0,   0, 255
  };
  int width = 3;
  int height = 3;

  Bitmap bmp = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
  var bitmapData = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, bmp.PixelFormat);
  Marshal.Copy(data, 0, bitmapData.Scan0, data.Length);
  bmp.UnlockBits(bitmapData);
  bmp.Save(@"c:\tmp.png");

此图像应如下所示:

这篇关于从字节数组创建PNG的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆