在C#中将RGB数组转换为图像 [英] Convert RGB array to image in C#
问题描述
我知道每个像素的rgb值,如何用C#中的这些值创建图片?我看过这样的例子:
I know the rgb value of every pixel, and how can I create the picture by these values in C#? I've seen some examples like this:
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;
}
但是它不起作用. 我有一个像这样的二维数组:
But it does not works. I have a two-dimensional array like this:
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}.
Each number correspond to a rgb value, for example, 1 => {244,166,89} 2=>{54,68,125}.
推荐答案
我将尝试以下代码,该代码对调色板使用256个Color
条目的数组(您必须预先创建并填充):
I'd try the following code, which uses an array of 256 Color
entries for the palette (you have to create and fill this in advance):
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 = palette[arrayIndex];
pic.SetPixel(x, y, c);
}
}
return pic;
}
我倾向于遍历像素,而不是数组,因为我发现读取双循环比单循环和取模/除法运算更容易.
I tend to iterate over the pixels, not the array, as I find it easier to read the double loop than the single loop and the modulo/division operation.
这篇关于在C#中将RGB数组转换为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!