How can I read image pixels' values as RGB into 2d array?

user1306322 picture user1306322 · Apr 12, 2012 · Viewed 96.9k times · Source

I was making a 2d map editor for my square tile platformer game, when I realized I could really use an image editor with its abilities to repaint adjacent pixels and many more, so I figured I should try and read a painted level by an app that will then convert it into a lightweigh format.

I'm not sure if using a bitmap format is mandatory for such thing, but I guess, reading a specific pixel would be easier than with PNG for example.

So my goal is to open an image, iterate through every pixel, look for those which colors fit my tile scheme and put corresponding tile into the array of blocks.

Note: I already have my lightweigh format, so I need only reading pixels values into array.


**Solution:** My sketch looks like this:
var myBitmap = new Bitmap(@"input.png");  

for (int x = 0; x < myBitmap.Width; x++)
    for (int y = 0; y < myBitmap.Height; y++)
    {                    
        Color pixelColor = myBitmap.GetPixel(x, y);
        // things we do with pixelColor
    }

Example 2:
var myBitmap = new Bitmap(@"input.png");

for (int x = 0; x < myBitmap.Width; x++)
{
    for (int y = 0; y < myBitmap.Height; y++)
    {
        // Get the color of a pixel within myBitmap.
        Color pixelColor = myBitmap.GetPixel(x, y);
        string pixelColorStringValue =
            pixelColor.R.ToString("D3") + " " +
            pixelColor.G.ToString("D3") + " " +
            pixelColor.B.ToString("D3") + ", ";

        switch (pixelColorStringValue)
        {
            case "255 255 255":
                {
                    // white pixel
                    break;
                }
            case "000 000 000":
                {
                    // black pixel
                    break;
                }
        }
    }
}

Answer

Itzack picture Itzack · Apr 12, 2012

Well, if I understood correctly, you want to iterate through the pixels in the image, perform some kind of test, and if it passes you want to store that pixel in an array. Here´s how you could do that:

using System.Drawing;

Bitmap img = new Bitmap("*imagePath*");
for (int i = 0; i < img.Width; i++)
{
    for (int j = 0; j < img.Height; j++)
    {
        Color pixel = img.GetPixel(i,j);

        if (pixel == *somecondition*)
        {
            **Store pixel here in a array or list or whatever** 
        }
    }
} 

Don´t think you need anything else. If you need the specific RGB values you can get them from the corresponding methods in the pixel object.