Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an image from URL to hex string?

Tags:

java

image

hex

I am downloading an image from URL as follows:

BufferedImage image = null;
URL url = new URL("http://www.ex.com/image/pic.jpg");
image = ImageIO.read(url);

I would like to convert it to something like the following hex string format:

89504E470D0A1A0A0000000D4948445200000124000001150802000000C6BD0FB3000000017352474200AECE1CE9000000097048597300000EC400000EC401952B0E1B000050B849444154785EED7D0B745CD759EE09E5618742A5C6F1833CB01A6E630587565E2154EE0D579203756DE823764B1ACAEB5A70EBAB2C08588EDB

But I don't know how to do that. How can I do that?

like image 787
becks Avatar asked Dec 30 '25 13:12

becks


2 Answers

You could do a combination of the following:

  1. Get byte array of image: Java- Convert bufferedimage to byte[] without writing to disk
  2. Get hex string of byte array: How to convert a byte array to a hex string in Java?
like image 63
Vincent van der Weele Avatar answered Jan 02 '26 02:01

Vincent van der Weele


To read a image into a byte array:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( image, "jpg", baos );
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();

And to show it as String:

public static String bytesToHex(byte[] bytes) {
    final char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    char[] hexChars = new char[bytes.length * 2];
    int v;
    for ( int j = 0; j < bytes.length; j++ ) {
        v = bytes[j] & 0xFF;
        hexChars[j * 2] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return new String(hexChars);
}
like image 23
elias Avatar answered Jan 02 '26 02:01

elias