繁体   English   中英

在Java中将1D字节图像数组转换为2D字节数组

[英]Convert 1D byte image array to 2D byte array in java

我有一个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)

一维数组的大小为26029,这显示了异常。

现在我该怎么办?

如何将一维图像转换为二维图像?

还是有人知道如何将图像转换为2D数组?

代替使用ByteArrayOutputStream使用DataBufferByte ,它将起作用。

DataBufferByte db = (DataBufferByte)image.getRaster().getDataBuffer();

            byte[] pixelarray = db.getData();

然后应用逻辑将一维数组转换为二维数组

这样可以提供正确的图像尺寸,并避免出现异常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM