输出图像的尺寸有些颠倒。对齐方式也被颠倒了。
BufferedImage theImage = new BufferedImage(h,w, BufferedImage.TYPE_BYTE_GRAY);
int [] pixtotal=new int [total_pixels];
for (int x = 0; x < w; x++)
{
for (int y = 0; y < h; y++)
{
int gray= image.getRGB(x, y)& 0xFF;
pixtotal[i]=gray;
i++;
}
}
File outputfile = new File("e:/bndwimage.jpg");
WritableRaster raster = (WritableRaster) theImage.getData();
raster.setPixels(0,0,h,w,pixtotal);
theImage.setData(raster);
ImageIO.write(theImage, "jpg", outputfile);
h
和 w
分别是高度和宽度。
为什么我得到的图像是错误的?
编辑:
P.S:我已经尝试了 w
和 h
的所有组合。
使用raster.setPixels(0,0,w,h,pixtotal)
设置raster
时,它给出:ArrayIndexOutOfBoundsException:坐标超出范围!
最佳答案
raster.setPixels(0,0,h,w,pixtotal);
根据 Oracle 文档,setPixels
采用参数 x、y、w、h、iArray
。您已经交换了宽度和高度,这在逻辑上会交换图像的尺寸。这也极大地改变了数组中像素的解析方式,而不会导致任何错误。
同样的问题也适用于您的new BufferedImage(h,w, BufferedImage.TYPE_BYTE_GRAY)
。
最后,我没有看到 i
的定义位置,但“增量 1”通常并不是将像素索引到一维数组中的方式。 x + (y * w)
应该是任何给定像素的正确索引。
关于java - 输出图像的尺寸错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21532553/