【问题标题】:Why BufferedImage is not working well?!! Is it because I misused it?为什么 BufferedImage 不能正常工作?!!是因为我用错了吗?
【发布时间】:2016-01-08 18:41:12
【问题描述】:

我想使用BufferedImage 将灰度图像从getRGB() 复制到int[][],然后再复制到setRGB()。问题是图像的大小与程序输出的大小不同。原始图像的文件大小 = 176 KB,而输出图像的文件大小 = 154 KB。我不得不说,当你看到这两个图像时,所有的人都会说它是相同的,但是就二进制位而言,我想知道一些不同的东西。

也许你们中的一些人会说没关系,只要你看的时候图像是一样的。事实上,在一些噪音项目的处理过程中,这是一个巨大的问题,我怀疑这就是我出现问题的原因。

我只是想知道除了BufferedImage 是否有其他方法来生成int[][] 然后创建输出?

这是我正在使用的代码:

public int[][] Read_Image(BufferedImage image)
{
  width = image.getWidth();
  height = image.getHeight();
  int[][] result = new int[height][width];
  for (int row = 0; row < height; row++)
     for (int col = 0; col < width; col++) 
        result[row][col] = image.getRGB(row, col);
  return result;
}

public BufferedImage Create_Gray_Image(int [][] pixels)
{
    BufferedImage Ima = new BufferedImage(512,512, BufferedImage.TYPE_BYTE_GRAY);
    for (int x = 0; x < 512; x++) 
    {
        for (int y = 0; y < 512; y++) 
        {
            int rgb = pixels[x][y];
            int r = (rgb >> 16) & 0xFF;
            int g = (rgb >> 8) & 0xFF;
            int b = (rgb & 0xFF);

            int grayLevel = (r + g + b) / 3;
            int gray = (grayLevel << 16) + (grayLevel << 8) + grayLevel; 
            Ima.setRGB(x, y, pixels[x][y]);
        }
    }
    return Ima;
}

 public void Write_Image(int [][] pixels) throws IOException
{
    File outputfile;
    outputfile = new File("Y0111.png");
    BufferedImage BI = this.Create_Gray_Image(pixels);
    ImageIO.write(BI, "png", outputfile);
    System.out.println("We finished writing the file");
}

看图,你看到文件大小 = 176 KB(这是原始图像)和文件大小 = 154 KB(这是输出图像)。

【问题讨论】:

  • 这很可能归结为图像格式和写入图像时使用的压缩级别
  • @MadProgrammer 好点子,你知道任何其他使压缩与输入相同的书写格式吗?
  • 我会先直接写出原始的 BufferedImage,看看是否有什么不同。另一个区别可能是原始图像使用的颜色模型
  • 输入图片是什么格式的?
  • 即使两个图像都是 PNG,灰色 PNG 仍然可以存储为具有完全相同像素值的灰色 (gray + A)、索引、RGB 或 RGBA。即使颜色模型相同,PNG 也有各种控制压缩的选项(快速压缩/较大尺寸,较慢压缩/较小尺寸)和隔行扫描选项。文件还可以包含 cmets 和元数据。因此,除非您自己编写这两个文件,否则几乎不可能拥有完全相同的位(甚至文件大小)。

标签: java image image-processing bufferedimage grayscale


【解决方案1】:

大小的差异不是问题。这肯定是因为不同的压缩/编码。

BufferedImage 实际上是一个大小为宽度 * 高度 * 通道的一维数组。 getRGB 不是操作 BufferedImage 的最简单/最快的方法。您可以使用 Raster(比 getRGB 快,不是最快,但它会为您处理编码)。对于灰度图像:

int[][] my array = new int[myimage.getHeight()][myimage.getWidth()] ;
for (int y=0 ; y < myimage.getHeight() ; y++)
    for (int x=0 ; x < myimage.getWidth() ; x++)
        myarray[y][x] = myimage.getRaster().getSample(x, y, 0) ;

相反的方式:

for (int y=0 ; y < myimage.getHeight() ; y++)
    for (int x=0 ; x < myimage.getWidth() ; x++)
        myimage.getRaster().setSample(x, y, 0, myarray[y][x]) ;

最快的方法是使用DataBuffer,但是你必须处理图像编码。

【讨论】:

  • 太棒了,是的,这就是我要找的东西,非常感谢..我测试过,它工作正常,输出大小与输入大小相同..
  • 很高兴它对您有用。但正如我所说,大小的差异肯定来自另一个问题。如果您想要最快的转换,请使用 DataBuffer,否则栅格就可以了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-16
  • 2019-01-04
相关资源
最近更新 更多