【问题标题】:Convert a BufferedImage into a 2D array将 BufferedImage 转换为 2D 数组
【发布时间】:2020-12-17 05:38:50
【问题描述】:

我有一个 BufferedImage,它代表一个 2048X2048 像素的 tiff 图像。我希望从 BufferedImage 中检索这样的数组 (int [2048][2048]。我应该如何进行?

【问题讨论】:

  • 欢迎来到 StackOverflow!它可以帮助您查看stackoverflow.com/help/how-to-ask。如果您已经对寻找解决方案进行了一些研究并展示了您的尝试,那么您更有可能获得有意义的答案。对您的一些关键字进行的快速 Google 搜索向我展示了许多潜在的解决方案,包括此站点上的一些答案,这可能是一个很好的起点。

标签: java


【解决方案1】:
arr = new int[2048][2048];

for(int i = 0; i < 2048; i++)
    for(int j = 0; j < 2048; j++)
        arr[i][j] = image.getRGB(i, j);

由于您可以从图像数据结构本身获取每个像素的 RGB 值,因此最好不要将所有内容复制到二维数组中。

【讨论】:

  • 如果速度是个问题,并且您知道图像类型的详细信息,您有时可以使用一些非健壮的代码(通常是一些强制转换) 查看 BufferedImage 内部。
【解决方案2】:

此方法将直接返回每个像素的红色、绿色和蓝色值,如果有 alpha 通道,它将添加 alpha 值。使用这种方法在计算指数方面比较困难,但比第一种方法快得多。

 private static int[][] convertTo2DWithoutUsingGetRGB(BufferedImage image) {

  final byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
  final int width = image.getWidth();
  final int height = image.getHeight();
  final boolean hasAlphaChannel = image.getAlphaRaster() != null;

  int[][] result = new int[height][width];
  if (hasAlphaChannel) {
     final int pixelLength = 4;
     for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) {
        int argb = 0;
        argb += (((int) pixels[pixel] & 0xff) << 24); // alpha
        argb += ((int) pixels[pixel + 1] & 0xff); // blue
        argb += (((int) pixels[pixel + 2] & 0xff) << 8); // green
        argb += (((int) pixels[pixel + 3] & 0xff) << 16); // red
        result[row][col] = argb;
        col++;
        if (col == width) {
           col = 0;
           row++;
        }
     }
  } else {
     final int pixelLength = 3;
     for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) {
        int argb = 0;
        argb += -16777216; // 255 alpha
        argb += ((int) pixels[pixel] & 0xff); // blue
        argb += (((int) pixels[pixel + 1] & 0xff) << 8); // green
        argb += (((int) pixels[pixel + 2] & 0xff) << 16); // red
        result[row][col] = argb;
        col++;
        if (col == width) {
           col = 0;
           row++;
        }
     }
  }

  return result;
 }

【讨论】:

  • 我已经在我的 tiff 图像上尝试过这种方法,结果是线程“main”中的异常 java.lang.ClassCastException: java.awt.image.DataBufferUShort 无法转换为 java.awt.image。第一行的DataBufferByte
  • 未找到 BufferedImage 和 DataBufferByte。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-16
  • 2014-08-31
  • 2011-01-09
  • 2017-07-29
相关资源
最近更新 更多