首页 > 解决方案 > Java:如何将二进制字符串转换为图像?

问题描述

我目前正在开发一种将图像转换为二进制字符串的工具,反之亦然。

要将图像转换为二进制,我使用以下方法:

public void toText(String imagePath, String textPath) throws IOException {
    BufferedImage image = ImageIO.read(new File(imagePath));

    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    ImageIO.write(image, "png", byteStream);

    byte[] bytes = byteStream.toByteArray();

    PrintWriter writer = new PrintWriter(new File(textPath));

    StringBuilder sb = new StringBuilder();
    for(byte b : bytes) {
        sb.append(String.format("%8s", Integer.toBinaryString(b & 0xFF)).replace(' ', '0'));
    }

    writer.write(sb.toString());
    writer.close();
}

.txt 文件中的输出将如下所示: "10001001010100000100111001000111000011010000101000011010000..." 我相信这段代码应该可以正常工作,如果我错了,请纠正我!

现在我想将字符串转换回图像。为此,我编写了以下代码:

public void toImage(String imagePath, String textPath) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader(new File(textPath)));
    String binary = reader.readLine();
    reader.close();

    byte[] bytes = new byte[binary.length() / 8];
    for(int i = 0; i < bytes.length; i++) {
        bytes[i] = Byte.parseByte((String) binary.subSequence(i * 8, i * 8 + 8), 2);
    }

    BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes));
    ImageIO.write(image, "png", new File(imagePath));
}

此代码的问题是,"10001001"例如,大于byte( 137) 的最大大小。那是因为"10001001"应该使用 2 的补码表示实际上转换为 value -119

我怎么解决这个问题?我如何知道何时使用“正常”二进制表示以及何时使用 2 的补码?

谢谢你。

标签: javaimagebinary

解决方案


你需要的是一个告诉你的标志。

A0表示不需要补码的数字。

A1代表你做的数字。

或者换句话说,一个标志告诉你数字是正数还是负数,这实际上是无符号数的存储方式。


推荐阅读