Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image to Byte Array to String (and vice versa)

I'd like to convert an image into a byte array, then convert that byte array into a string. Also, I'd then like to convert that string back to a byte array, and finally back to an image. How might I go about accomplishing this? Any help will be appreciated.

like image 794
Adham Avatar asked Feb 22 '11 21:02

Adham


1 Answers

  1. Use ImageIO.write(..) and pass a ByteArrayOutputStream. Then call stream.toByteArray() - you have the bytes.

  2. Use base64 or hex to represent the byte array as string - commons-codec has Base64 and Hex which allow conversion in both directions. So now you have the string

  3. See 2 - convert from string to byte array. Now you have the byte[] again.

  4. Use ImageIO.read(..) and pass a new ByteArrayInputStream(bytes)

(for point 2 and 3 you can use new String(bytes, "utf-8") and string.getBytes("utf-8"), but prefer base64)

like image 174
Bozho Avatar answered Nov 19 '22 05:11

Bozho