在java中将file.bmp转换为二进制文件,并将二进制文件转换回file.bmp

kupeojn6  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(359)

我正在尝试将图像(.bmp)转换为二进制代码,然后对其进行处理,然后再转换回来。让我们把处理部分去掉,只关注转换。
我现在设法将图像转换为二进制:

// Image to byte[]
    File file = new File("image.bmp");
    BufferedImage bufferedImage = ImageIO.read(file);
    WritableRaster raster = bufferedImage.getRaster();
    DataBufferByte data = (DataBufferByte) raster.getDataBuffer();

   // byte[] to binary String
   String string = "";
    for (byte b : data.getData()) {
        String substring = Integer.toBinaryString((b & 0xFF) + 0x100).substring(1);
        string = string.concat(substring);
    }

  // Binary string to binary LinkedList<Ingeger> - this part is optional
  LinkedList<Integer> vector = new LinkedList<>();
    for (char c : stringVector.toCharArray()) {
        if (c == '0' || c == '1') {
            vector.add((int) c - 48);

        } else {
            System.out.println("Incorrect value.");
            break;
        }
    }

此时,我正在将文件(.bmp)转换为二进制向量。我不确定它是否正确。
另一个问题是将其转换回.bmp文件。我需要将二进制向量(或字符串)转换为 byte[] 然后回到 File 或图像。
我相信最后一步是这样的:

FileOutputStream fileOutputStream = new FileOutputStream("output.bmp");
        fileOutputStream.write(byteArrayFromBinary.getBytes());

有人能帮我弄清楚吗?因为我不知道这到底是怎么回事。如果有任何建议,我将不胜感激。

a11xaf1n

a11xaf1n1#

所以经过大量的研究终于想出了解决办法。
要将.bmp格式的BuffereImage转换为二进制:

public String imageToVector(BufferedImage image) throws Exception {
        String vectorInString = "";
        for (int x = 0; x < image.getWidth(); x++) {
            for (int y = 0; y < image.getHeight(); y++) {
                Color color = new Color(image.getRGB(x, y), false);
            vectorInString = vectorInString.concat(decimalToBinary(color.getRed()));
            vectorInString = vectorInString.concat(decimalToBinary(color.getGreen())); 
            vectorInString = vectorInString.concat(decimalToBinary(color.getBlue())); 
            }
        }
        return vectorInString;
}

要将二进制矢量转换回.bmp格式的BuffereImage,请执行以下操作:

String[] splittedString = vectorInString.split("(?<=\\G.{8})");

    int i = 0;
    for (int x = 0; x < image.getWidth(); x++) {
        for (int y = 0; y < image.getHeight(); y++) {
            int red = Integer.parseInt(splittedString[i], 2); 
            i++;
            int green = Integer.parseInt(splittedString[i], 2); 
            i++;
            int blue = Integer.parseInt(splittedString[i], 2); 
            i++;

            Color color = new Color(red, green, blue);

            image.setRGB(x, y, color.getRGB());
        }
    }

如果你有任何其他问题,请问,我可以解释为什么我需要这个解决方案。

相关问题