Borislav Georgiev
Borislav Georgiev

Reputation: 33

How to convert image to hexstring using JAVA (1.5)?

I've been struggling with this for some time, and since I'm originally not a programmer, I'd appreciate any help.Here's the situation:

1. I have an image file on the file system, as well as converted to byteArrayOutputStream and to a ByteArray.(currently it's not critical which to choose, so any of these will work fine for input data)

2. I need to have the image represented as a string with the HEX code and a 0x prefix, like this:

Image -> String = '0xFFD8FFE000104A46494600010200000100010000FFDB0'

Thanks in advance to anyone who tries to help! Any sample code or library will be appreciated!

Upvotes: 1

Views: 6114

Answers (5)

belmel ahmed
belmel ahmed

Reputation: 356

this work with me

InputStream in = new FileInputStream(Image); 
          int c;
          String str="";
          while ((c = in.read()) != -1) {
        str +=  Integer.toString( ( c & 0xff ) + 0x100, 16).substring( 1 );
         }

Upvotes: 0

Tho
Tho

Reputation: 25080

I think you should not use HexString to store Image as string because it gains

data a lots.

You should use base-64 encoding for saving instead of hex encoding.

I recommend you to use Base64 util of apache commons-codec

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691785

Using Apache commons-codec:

String s = "0x" + Hex.encodeHexString(bytes);

Upvotes: 1

Borislav Georgiev
Borislav Georgiev

Reputation: 33

This is the code that worked for me:

public static String getHexString(byte[] b) throws Exception {
  String result = "";
  for (int i=0; i < b.length; i++) {
    result +=
          Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
  }
  return result;
}

Thanks for the help anyway!

Upvotes: 1

Doszi89
Doszi89

Reputation: 357

There's nothing like ready library to convert image to hex.You have to check this one topic:

Java: File to Hex? :)

And if your hex is ready, you can convert it to string with method from another answer of @JB Nizet or try this library:

String hex = HexBin.encode(bytes[]); // add "0x" of course.

Upvotes: 0

Related Questions