如何将图像像素的值作为 RGB 读取到二维数组中? [英] How can I read image pixels' values as RGB into 2d array?

查看:52
本文介绍了如何将图像像素的值作为 RGB 读取到二维数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的方形平铺平台游戏制作 2d 地图编辑器,当我意识到我真的可以使用具有重新绘制相邻像素等功能的图像编辑器时,所以我想我应该尝试阅读绘制的关卡然后将其转换为轻量级格式的应用程序.

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.

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

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.

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

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
    }


示例 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;
                }
        }
    }
}

推荐答案

好吧,如果我理解正确,你想遍历图像中的像素,执行某种测试,如果通过你想存储它数组中的像素.这样做的方法如下:

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** 
        }
    }
} 

不要认为您需要其他任何东西.如果需要具体的RGB值,可以通过像素对象中的相应方法获取.

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.

这篇关于如何将图像像素的值作为 RGB 读取到二维数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆