如何将2d byte [] []数组(二进制图像数组)转换为图像java

时间:2015-02-11 15:47:23

标签: java arrays image-processing 2d

您好我想将2D byte [] []数组转换为图像。 我已将黑白图像转换为2D byte [] []数组,并希望将2d字节数组转换为图像。

1 个答案:

答案 0 :(得分:-1)

将2D阵列转换为1D阵列

要将byte - 数组写入BufferedImage,它必须(据我所知)是一维数组。您可以使用这些简单的循环将二维字节数组(byte[][])转换为一维字节数组(byte[]):

/*
 * Create a new 1-dimensional byte array which will hold the result
 * Set its size to the item count in the pixelData array
 */
byte[] oneDimArray = new byte[pixelData.length * pixelData[0].length];

/*
 * Loop through the "horizontal" row in the pixelData array
 */
for(int x = 0; x < pixelData.length; x++) {
    /*
     * Loop through each item in the current vertical row
     */
    for(int y = 0; y < pixelData[x].length; y++) {
        /*
         * Set each item in the 1-dimensional array to the corresponding
         * item in the 2-dimensional array
         */
        oneDimArray[x + y * pixelData.length] = twoDimArray[x][y];
    }
}

将字节数组转换为BufferedImage

现在,您可以使用以下简单代码将byte - 数组写入新的BufferedImage

ByteArrayInputStream byteIn = new ByteArrayInputStream(oneDimArray);
BufferedImage finalImage = ImageIO.read(byteIn);

Taken from here

现在您可以将BufferedImage用于任何您想要的内容,并且希望它在转化之前看起来像是这样。

相关问题