Adham
Adham

Reputation: 64904

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.

Upvotes: 6

Views: 11181

Answers (1)

Bozho
Bozho

Reputation: 597224

  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)

Upvotes: 7

Related Questions