c# - 如何将图像像素值作为 RGB 读取到二维数组中?

标签 c# image bitmap rgb

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

我不确定对于此类事情是否必须使用位图格式,但我猜,读取特定像素比使用 PNG 更容易。

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

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


**解决方案:** 我的草图如下所示:
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;
                }
        }
    }
}

最佳答案

好吧,如果我没理解错的话,你想遍历图像中的像素,执行某种测试,如果它通过了,你想将该像素存储在数组中。以下是您可以如何做到这一点:

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 值,您可以从像素对象中的相应方法中获取它们。

关于c# - 如何将图像像素值作为 RGB 读取到二维数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10127871/

相关文章:

c# - 图像比较和返回百分比

image-processing - 如何检测和更正位图中的虚线或形状?

c# - 正则表达式检测连字符

c# - 在按钮中添加 OnClientClick 时必填字段验证器不起作用

c# - 使用 C# 自动设置 Internet Explorer/Windows 以使用 Socks5 代理

c# - 如何禁止用户在 WFFM (sitecore) 中使用自定义电子邮件操作附加大文件?

javascript - 无论在哪里使用,我如何触发图像重新加载(CSS 背景图像、伪元素、样式属性、img 标签)

image - 流体图像的最大宽度和最大高度在 IE10 中不起作用

c++ - 阅读 PPM 图像问题

java - Last.fm 不会返回艺术家图像