0

I have to read JPEG pictures from a database. 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. This is a valid JPEG and can be rendered in a browser. I have tried to reproduce this in 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

ÿØÿà 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. The resulting file is no jpg. What is Notepad++ doing and how can I reproduce this in Java? Any advise would be greatly appreciated.

user207421
  • 305,947
  • 44
  • 307
  • 483
Hans
  • 145
  • 9
  • Use a tool that can binary compare the files and let you see the result. You most likely have swapped byte order. – Thorbjørn Ravn Andersen Jul 30 '20 at 09:14
  • Why isnt it a jpg? `ÿØ` are the characters of the bytes `FF D8`, which is the jpg "Start Of Image" header. – f1sh Jul 30 '20 at 09:16
  • 1
    Could it be a JFIF? (there is litterally written JFIF) EDIT: look at that for more information https://en.wikipedia.org/wiki/JPEG_File_Interchange_Format – loicEzt Jul 30 '20 at 09:17
  • Java will encode from char to byte when you write to a file. At this time, you need to use `ISO-8859-1` as the character set. Don't use `UTF-8`. –  Jul 30 '20 at 09:24
  • Possible duplicate of : https://stackoverflow.com/questions/13990941/how-to-convert-hex-string-to-java-string – Julien D. Jul 30 '20 at 09:26
  • 1
    *Why* are they stored as hex strings? Why not a BLOB? And if you must, why Java code? Surely the database has a de-hexing function? And surely what you want is not hex to ASCII but hex to binary? – user207421 Jul 30 '20 at 23:28

1 Answers1

0

Do not convert the file contents to ASCII, UTF-8, ISO-8859-1 or other character encodings! JPEG files are binary files, and don't need encoding.

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();
}
Harald K
  • 26,314
  • 7
  • 65
  • 111