Hex String to Image

前端 未结 2 1128
梦谈多话
梦谈多话 2021-01-25 14:52

I have a hex string which looks like:

String hexImage =\"0xFFD8FFE000104A46494600010200006400640000FFEC00114475636B79000100040000003C...\"

Whi

相关标签:
2条回答
  • 2021-01-25 15:07

    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);
    

    or at the end, such as this:

    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.

    EDIT: In addition, as Peter Lawrey indicated in his comment, you should check whether the decode method expects 0x in front of the string.

    0 讨论(0)
  • 2021-01-25 15:08

    for even length string

     public static byte[] hexStringToByteArray(String str) {
        try {
    
    
            String s = str;
            int len = s.length();
            byte[] data = new byte[len / 2];
            for (int i = 0; i < len; i += 2) {
                if (i == len - 1) {
                     System.out.println("in correct");                   
                } else {
    
                    data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                            + Character.digit(s.charAt(i + 1), 16));
    
    
                }
            }
            return data;
        } catch (StringIndexOutOfBoundsException sex) {
    
            writeDirtyData(str.substring(0, str.indexOf(",")));
        }
        return null;
    }
    

    Non of Odd hex string is correct. Check source from you get this string . It is because of truncation of string due to limit no of characters. If String is image is stored in database then retrieve it using program not using any tools

    I was having same problem with .net and MSSQL and by using webservice and Java Client I tried all conversion and library including axis and util jpg.

    0 讨论(0)
提交回复
热议问题