简体   繁体   中英

How to convert an image from URL to hex string?

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?

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?

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

Just get the image in byte[] flavor the usual Java I/O way and feed that in turn to DataTypeConverter#printHexBinary() to get a hex string out of it.

ByteArrayOutputStream output = new ByteArrayOutputStream();

try (InputStream input = new URL("http://example.com/some.jpg").openStream()) {
    byte[] buffer = new byte[10240];
    for (int length = 0; (length = input.read(buffer)) > 0;) {
         output.write(buffer, 0, length);
    }
}

String hex = DatatypeConverter.printHexBinary(output.toByteArray());
// ...

Note that you don't need the whole Java 2D API ( ImageIO et.al.) for this. This is only useful if you actually intend to manipulate the image (resize, crop, skew, etc).

In addition to the other answers, once you have read the image, you can also use the existing javax.xml.bind.DatatypeConverter class to convert the byte array to a hex string. Ideally use the approach from @BalusC to save memory and directly read the image into a byte array, and then simply do

String s = javax.xml.bind.DatatypeConverter.printHexBinary(byteArray);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM