我想使用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(这是输出图像)。
答案 0 :(得分:1)
尺寸的差异不是问题。这当然是因为不同的压缩/编码。
BufferedImage实际上是一个大小为* height * channel的一维数组。 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,但是你必须处理图像编码。