我有缓冲图像的1D字节数组。我想把它转换成2D字节数组,为此我写了下面的代码
File file = new File("/home/tushar/temp.jpg");
try {
input_bf = ImageIO.read(file);
width = input_bf.getWidth();
height = input_bf.getHeight();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte [][] image = new byte[width][height];
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ImageIO.write(input_bf, "jpg", bos );
bos.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] imageInByte = bos.toByteArray();
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//here is the main logic to convert 1D to 2D
int x=0;
for(int i=0;i<width;i++)
{
for(int j=0;j<height;j++)
{
image[i][j] = imageInByte[x];
x++;
}
}
但我得到了像这样的例外
java.lang.ArrayIndexOutOfBoundsException: 26029
at smoothing.main(smoothing.java:70)
1D阵列的大小为26029,显示了例外情况。
现在我该怎么办?
如何将1D图像阵列转换为2D图像阵列?
或者任何人都知道如何将图像转换为2D阵列吗?
与其使用ByteArrayOutputStream
,不如使用DataBufferByte
。
DataBufferByte db = (DataBufferByte)image.getRaster().getDataBuffer();
byte[] pixelarray = db.getData();
然后应用该逻辑将1D阵列转换为2D阵列
这样可以提供正确的图像大小并避免出现异常。