【问题标题】:Two-dimensional RGB array to BufferedImage二维 RGB 数组到 BufferedImage
【发布时间】:2015-11-10 21:54:34
【问题描述】:

我有一个自定义的 RGB 类:

class RGB {
    int R, G, B;
}

我制作了一个代表图像的 RGB 对象的二维数组:

RGB[][] image = new RGB[HEIGHT][WIDTH];

for (int i = 0; i < HEIGHT; i++) {
    for (int j = 0; j < WIDTH; j++) {
        int pixel = bufferedImage.getRGB(i, j);
        int red = (pixel >> 16) & 0xff;
        int green = (pixel >> 8) & 0xff;
        int blue = (pixel) & 0xff;
        image[i][j] = new RGB(red, green, blue);
    }
}

现在我想对该数组进行一些更改并将其保存为 BufferedImage。 基本上,我可以做这样的事情:

BufferedImage newImage = new BufferedImage(HEIGHT, WIDTH, BufferedImage.TYPE_INT_RGB);
for (int i = 0; i < HEIGHT; i++) {
    for (int j = 0; j < WIDTH; j++) {
        newImage.setRGB(i, j, VALUE);
    }
}

但我需要将每个像素的 RGB 字段转换为一个整数 VALUE,我不知道该怎么做。 或者也许有更简单的方法来做到这一点?

【问题讨论】:

  • 为什么不只是((red &amp; 0xff) &lt;&lt; 16) | ((green &amp; 0xff) &lt;&lt; 8) | (blue &amp; 0xff)
  • 您是否考虑过使用DirectColorModel 对象而不是使用您的自定义RGB 类?看起来它会做你目前正在做的事情,并提供一种方法来获取你正在寻找的 int 值。
  • 这成功了,谢谢。

标签: java image rgb bufferedimage


【解决方案1】:

注意,getRGB 函数是 bufferedImage.getRGB(x, y),而你做的正好相反(x 和 y 倒置)。

现在您可以使用 Raster 或 DataBuffer:

  1. newimage.getRaster().setSample(x, y, 0, VALUE)
  2. int[] newimagebuffer = ((DataBufferInt)newimage.getRaster().getDataBuffer).getData() 然后 newimagebuffer[x​​+y*WIDTH] = VALUE。

如果您不知道图像类型并且不想重复代码,我推荐使用 Raster,但否则,使用 DataBuffer 访问和修改图像值肯定更快,因为您可以直接访问数组。并且 TYPE_INT_RGB 不是最实用的图像格式,因为您每次都必须将三元组 RGB 解压缩/压缩为 int。您可以使用 TYPE_3BYTE_BGR。

【讨论】:

    猜你喜欢
    • 2012-08-30
    • 2020-05-15
    • 1970-01-01
    • 2011-07-23
    • 2013-11-23
    • 1970-01-01
    • 1970-01-01
    • 2017-12-06
    • 1970-01-01
    相关资源
    最近更新 更多