[英]Java JPEG hex to ASCII
I have to read JPEG pictures from a database.我必须从数据库中读取 JPEG 图片。 They are stored as Hex Strings.
它们存储为十六进制字符串。 For tests I have saved the original hex String to a file, opened it with Notepad++ and applied
Convert -> HEX --> ASCII
and saved the result.对于测试,我已将原始十六进制字符串保存到一个文件中,用 Notepad++ 打开它并应用
Convert -> HEX --> ASCII
并保存结果。 This is a valid JPEG and can be rendered in a browser.这是一个有效的 JPEG,可以在浏览器中呈现。 I have tried to reproduce this in java.
我试图在 java 中重现这一点。
private String hexToASCII(String hex) {
StringBuilder output = new StringBuilder();
for (int i = 0; i < hex.length(); i+=2) {
String str = hex.substring(i, i+2);
output.append((char)Integer.parseInt(str, 16));
}
return output.toString();
}
When I save the result to disk, the resulting file is no jpg it begins with当我将结果保存到磁盘时,生成的文件不是以它开头的 jpg
ÿØÿà JFIF ÿÛ C
If have also tried to convert the original hex string with https://www.rapidtables.com/convert/number/hex-to-ascii.html this gives the same result as my code.如果还尝试使用https://www.rapidtables.com/convert/number/hex-to-ascii.html转换原始十六进制字符串,这将给出与我的代码相同的结果。 The resulting file is no jpg.
结果文件不是jpg。 What is Notepad++ doing and how can I reproduce this in Java?
Notepad++ 在做什么,如何在 Java 中重现它? Any advise would be greatly appreciated.
任何建议将不胜感激。
Do not convert the file contents to ASCII, UTF-8, ISO-8859-1 or other character encodings!请勿将文件内容转换为 ASCII、UTF-8、ISO-8859-1 或其他字符编码! JPEG files are binary files, and don't need encoding.
JPEG 文件是二进制文件,不需要编码。
I suggest:我建议:
private void hexToBin(String hex, OutputStream stream) {
for (int i = 0; i < hex.length(); i += 2) {
String str = hex.substring(i, i + 2);
stream.write(Integer.parseInt(str, 16));
}
}
And perhaps:也许:
private byte[] hexToBin(String hex) {
ByteArrayOutputStream stream = new ByteArrayOutputStream(hex.length() / 2);
hexToBin(hex, stream);
return stream.toByteArray();
}
You should write the string to a file like this.您应该将字符串写入这样的文件。
String s = hexToASCII(hex);
Files.writeString(Paths.get("filename.jpg"), s, StandardCharsets.ISO_8859_1);
In Java, when writing a string to a file, char is encoded into byte depending on the character set.在 Java 中,将字符串写入文件时,根据字符集将 char 编码为字节。 The character set
ISO_8859_1
encodes one character straight into one byte.字符集
ISO_8859_1
将一个字符直接编码为一个字节。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.