How to create a Bitmap from a Color[][]?

Asked

Viewed 78 times

4

I had to transform a Bitmap into Color[][] to apply some algorithms and need to recreate the bitmap. There is an easy way to do this?

To turn the bitmap into Color[][] I did what is below. There is an easier way?

    public Color[][] GetPixels(Bitmap b1)
    {
        int hight = b1.Height;
        int width = b1.Width;

        Color[][] colorMatrix = new Color[width][];
        for (int i = 0; i < width; i++)
        {
            colorMatrix[i] = new Color[hight];
            for (int j = 0; j < hight; j++)
            {
                colorMatrix[i][j] = b1.GetPixel(i, j);
            }
        }
        return colorMatrix;
    }
  • You can create a new bitmap (class Bitmap with the array dimensions) and then traverse the array elements to define each pixel of the bitmap with the given value using the method SetPixel. You can try to infer an example from of this my answer in another question. I won’t answer because I don’t know, in fact, if this is the best form in C#. Maybe I have some appropriate constructor. Worth checking out.

  • 1

    That what you said is what I’m doing here. I’ll keep looking if there’s an easier way and if I find myself I put here.

  • There is no Bitmap constructor that accepts a two-dimensional Color matrix, so the way you are doing it is the only possible...!

1 answer

0

Unfortunately there is no constructor or method for Bitmap that even accepts a two-dimensional array (as noted in the comments). The solution given in Luiz Vieira’s comments would be an appropriate method. Something like that (untested!):

public Bitmap SetPixels(Color[][] colors)
{
    int hight = colors.GetLength(1);
    int width = colors.GetLength(0);

    Bitmap b1 = new Bitmap();
    for (int i = 0; i < width; i++)
    {
        colorMatrix[i] = new Color[hight];
        for (int j = 0; j < hight; j++)
        {
            b1.SetPixel(i,j,colors[i][j]);
        }
    }
    return b1;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.