如何将图像像素的值作为RGB读入2d数组?

use*_*322 21 c# rgb image bitmap

我正在为我的方形平台平台游戏制作一个二维地图编辑器,当我意识到我真的可以使用一个图像编辑器,它能够重新绘制相邻的像素等等,所以我想我应该尝试通过应用程序读取绘制的水平然后将其转换为轻量级格式.

我不确定是否使用位图格式是必须的,但我猜,读取特定像素比使用PNG更容易.

所以我的目标是打开一个图像,遍历每个像素,寻找那些适合我的图块方案的颜色,并将相应的图块放入块数组中.

注意:我已经有了轻量级格式,所以我只需要将像素值读入数组.


解决方案:我的草图如下所示:

Bitmap 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
                }
            }
Run Code Online (Sandbox Code Playgroud)


例2:

Bitmap 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;
                            }
                    }
                }
            }
Run Code Online (Sandbox Code Playgroud)

小智 38

好吧,如果我理解正确,你想迭代图像中的像素,执行某种测试,如果它通过你想要将该像素存储在数组中.以下是如何做到这一点:

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** 
        }
    }
} 
Run Code Online (Sandbox Code Playgroud)

不要以为你还需要别的东西.如果需要特定的RGB值,可以从像素对象的相应方法中获取它们.

  • 对于想要创建RGB字节数组的人来说,你可以使用类似:`int offset = y*bitmap.Width*3 + x*3; rgbBytes [offset + 0] = pixel.R; rgbBytes [offset + 1] = pixel.G; rgbBytes [偏移+ 2] = pixel.B;`注意如何坐标`x`和`y`是混乱的一个共同的源(x是列和y是行).应该很明显如何使其适用于RGBA,BGR等. (2认同)