我目前正在开发一种工具,可以将图像转换为二进制字符串,或者将图像转换为二进制字符串。
要将图像转换为二进制,我使用以下方法:
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"
大于字节
的最大大小 (137
)。这是因为 "10001001"
实际上应该使用 2 的补码表示法转换为值 -119
。
如何解决这个问题?我如何知道何时使用“正常”二进制表示形式以及何时使用 2 的补码?
谢谢。
最佳答案
您需要的是一个告诉您这一点的标志。
A 0
表示不需要补码的数字。
A 1
代表您所在位置的数字。
或者换句话说,一个标志可以告诉您该数字是正数还是负数,这实际上是无符号数的存储方式。
关于Java:如何将二进制字符串转换为图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58476666/