java - 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 的补码?
谢谢你。
解决方案
你需要的是一个告诉你的标志。
A0
表示不需要补码的数字。
A1
代表你做的数字。
或者换句话说,一个标志告诉你数字是正数还是负数,这实际上是无符号数的存储方式。
推荐阅读
- c# - 如何从转发器导出的 excel 中删除前两列和超链接
- perl - Async.pm 中的 AsyncTimeout 仅在完成异步进程执行后才给出超时
- python - 在括号之间提取什么正则表达式?
- python - 我正在与在 discord.py 中具有一定作用的 dming 成员作斗争
- xcode12 - macOS Big Sur - 运行任何项目或 .swift 文件时 Xcode 12.2/12.4 冻结
- winforms - 如何根据类型在列中显示不同的单元格?
- sql - 如何添加 19 代替 00?
- c# - Outlook vsto - 属性处理
- javascript - 单击第二次时如何删除第一次单击的活动类列表?
- java - JSON Schema 验证 - 两个值不应同时为 false