gpt4 book ai didi

java - 为什么 BufferedImage 不能正常工作?!!是因为我用错了吗?

转载 作者:行者123 更新时间:2023-11-30 07:41:15 25 4
gpt4 key购买 nike

我想使用 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(这是输出图像)。

enter image description here

最佳答案

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

BufferedImage实际上是一个尺寸为宽*高* 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,但随后您必须处理图像编码。

关于java - 为什么 BufferedImage 不能正常工作?!!是因为我用错了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34668140/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com