【问题标题】:Java: How to convert a binary string to an image?Java:如何将二进制字符串转换为图像?
【发布时间】:2020-02-16 23:23:24
【问题描述】:

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

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

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 的补码表示形式转换为值 -119

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

谢谢。

【问题讨论】:

    标签: java image binary


    【解决方案1】:

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

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

    1 表示您所在的号码。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-10
      • 2013-02-11
      • 1970-01-01
      • 2016-01-14
      • 2015-06-21
      • 2014-10-24
      • 2013-01-30
      • 1970-01-01
      相关资源
      最近更新 更多