在C#中将RGB数组转换为图像

4

我知道每个像素的RGB值,那么如何在C#中通过这些值创建图片呢?我看到了一些类似这样的例子:

public Bitmap GetDataPicture(int w, int h, byte[] data)
  {

  Bitmap pic = new Bitmap(this.width, this.height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
  Color c;

  for (int i = 0; i < data.length; i++)
  {
    c = Color.FromArgb(data[i]);
    pic.SetPixel(i%w, i/w, c);
  }

  return pic;
  } 

但它并不起作用。

我有一个二维数组,像这样:

1 3 1 2 4 1 3 ...
2 3 4 2 4 1 3 ...
4 3 1 2 4 1 3 ...
...

每个数字对应一个RGB值,例如,1 => {244,166,89},2 => {54,68,125}。


你不知道如何创建字节数组吗??那你如何创建任何数组呢... 某种类型[] myname = ... - BugFinder
可能是以下问题的重复:如何从字节数组创建位图? - slawekwin
你的确切需求是什么? 你需要创建一个具有每个像素RGB的位图图像或从图像创建字节数组。 - Uthistran Selvaraj
创建一个位图图像,其中每个像素的RGB。 - hashtabe_0
你有每个像素的RGB值,对吧?而且你知道要创建的图像的高度和宽度,对吧? - Uthistran Selvaraj
显示剩余9条评论
2个回答

4
我会尝试使用下面的代码,它使用了一个包含256个Color条目的数组作为调色板(您需要提前创建并填充此数组):

public Bitmap GetDataPicture(int w, int h, byte[] data)
{
    Bitmap pic = new Bitmap(w, h, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

    for (int x = 0; x < w; x++)
    {
        for (int y = 0; y < h; y++)
        {
            int arrayIndex = y * w + x;
            Color c = Color.FromArgb(
               data[arrayIndex],
               data[arrayIndex + 1],
               data[arrayIndex + 2],
               data[arrayIndex + 3]
            );
            pic.SetPixel(x, y, c);
        }
    }

    return pic;
} 

我倾向于遍历像素,而不是数组,因为我发现双重循环比单重循环和模除运算更易阅读。

如何声明调色板变量? - Inside Man
@InsideMan 实际上这是我的代码中的一个错误。"palette" 变量应该是 "data" 变量,它有 w * h * 4 字节长,并包含每个像素的 ARGB 值。 - Thorsten Dittmar

0

你的解决方案非常接近可工作的代码。你只需要“调色板” - 即由3个元素的字节数组组成的集合,其中每个3字节元素包含{R,G,B}值。

    //palette is a 256x3 table
    public static Bitmap GetPictureFromData(int w, int h, byte[] data, byte[][] palette)
    {
      Bitmap pic = new Bitmap(w, h, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
      Color c;

      for (int i = 0; i < data.Length; i++)
      {
          byte[] color_bytes = palette[data[i]];
          c = Color.FromArgb(color_bytes[0], color_bytes[1], color_bytes[2]);
          pic.SetPixel(i % w, i / w, c);
      }

      return pic;
    }

这段代码在我的电脑上可以运行,但是速度比较慢。
如果你先将BMP文件创建成内存中的“图像”,然后使用Image.FromStream(MemoryStream("image")),那么代码就会变得更快,但是这样需要处理的东西比较多。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接