Hex String to Image [英] Hex String to Image
问题描述
我有一个十六进制字符串,如下所示:
I have a hex string which looks like:
String hexImage ="0xFFD8FFE000104A46494600010200006400640000FFEC00114475636B79000100040000003C..."
我需要使用Java转换为图像。我已经尝试使用org.apache.commons.codec.binary.Hex类首先转换为字节数组。 FileOutputStream稍后将其转储到文件中。
Which I need to convert to an image using Java. I've tried converting to a byte array first with org.apache.commons.codec.binary.Hex class. FileOutputStream later dumps this to a file.
char[] charArr= hexImage.toCharArray();
byte[] byteArray = Hex.decodeHex(charArr);
然而,Hex类中的解析器会窒息,并带有Decoder异常:奇数个字符。无论我使用什么方法转换为字节数组,它都会失败。 fileformat肯定是JPEG。
however the parser in the Hex class chokes, with an Decoder exception : Odd number of characters. No matter what method I use to convert to a byte array, it fails. The fileformat is definitely a JPEG.
我尝试从字符串中删除 this 0xFF,但此时图像已损坏。 0xFF我认为是罪魁祸首 - 有什么想法我需要做些什么才能纠正这个问题?
I've tried removing this 0xFF from the string, but the image is corrupt at this point. 0xFF I assume is a the culprit - anyone any ideas on what do I need to do to correct this?
推荐答案
通常,每个人byte由2个十六进制数字表示,因此,如果你的HEX字符串中有一个奇数位数,那么它就有问题了。您可以尝试在开头填充0,例如:
Normally, each byte is represented by 2 hex digits, therefore, if you have an odd number of digits in your HEX string, then something is wrong with it. You can try padding it with 0 in the beginning, such as this:
String hexImage ="0xFFD8FFE000104A46494600010200006400640000FFEC00114475636B79000100040000003C...";
if(hexImage.length()%2 == 1)
hexImage = "0x0" + hexImage.substring(2);
或最后,例如:
String hexImage ="0xFFD8FFE000104A46494600010200006400640000FFEC00114475636B79000100040000003C...";
if(hexImage.length()%2 == 1)
hexImage += "0";
然而,这不能保证产生合适的图像。
However this is not guaranteed to produce a proper image.
总的来说,你应该检查你是如何获得十六进制字符串的。正确的字节序列应始终包含偶数个十六进制数字。
On the whole, you should check how you get your hex string. A proper byte sequence should always contain an even number of hex digits.
编辑:此外,正如Peter Lawrey在评论中指出的那样,应检查 decode
方法是否在字符串前面需要 0x
。
In addition, as Peter Lawrey indicated in his comment, you should check whether the decode
method expects 0x
in front of the string.
这篇关于Hex String to Image的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!