【发布时间】: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 的补码?
谢谢。
【问题讨论】: