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

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

我不确定是否使用位图格式是必须的,但我想,读取特定像素比使用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 } } 

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

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

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

  public Color[][] getBitmapColorMatrix(string filePath) { Bitmap bmp = new Bitmap(filePath); Color[][] matrix; int height = bmp.Height; int width = bmp.Width; if (height > width) { matrix = new Color[bmp.Width][]; for (int i = 0; i <= bmp.Width - 1; i++) { matrix[i] = new Color[bmp.Height]; for (int j = 0; j < bmp.Height - 1; j++) { matrix[i][j] = bmp.GetPixel(i, j); } } } else { matrix = new Color[bmp.Height][]; for (int i = 0; i <= bmp.Height - 1; i++) { matrix[i] = new Color[bmp.Width]; for (int j = 0; j < bmp.Width - 1; j++) { matrix[i][j] = bmp.GetPixel(i, j); } } } return matrix; } 

我想我曾做过类似的事情。 这是我正在做的代码片段:

 public static void main(String[] args) { try { String path = "src/colors.jpg"; BufferedImage image = ImageIO.read(new File(path)); int w = image.getWidth(); int h = image.getHeight(); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { Color c = new Color(image.getRGB(x, y)); int red = c.getRed(); int green = c.getGreen(); int blue = c.getBlue(); countColor(red, green, blue); totalCount++; } } printColors(); } catch (Exception ex) { System.out.println(ex.getMessage()); } } 

在内部for循环中,您可以将某些东西放入数组[i] [j]中。 (如果那是你要找的)