Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert RGB array to image in C#

Tags:

c#

image

bitmap

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

Each number correspond to a rgb value, for example, 1 => {244,166,89} 2=>{54,68,125}.

like image 604
hashtabe_0 Avatar asked Oct 20 '25 14:10

hashtabe_0


1 Answers

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 = Color.FromArgb(
               data[arrayIndex],
               data[arrayIndex + 1],
               data[arrayIndex + 2],
               data[arrayIndex + 3]
            );
            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.

like image 80
Thorsten Dittmar Avatar answered Oct 22 '25 02:10

Thorsten Dittmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!