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.
Use ImageIO.write(..)
and pass a ByteArrayOutputStream
. Then call stream.toByteArray()
- you have the bytes.
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
See 2 - convert from string to byte array. Now you have the byte[]
again.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With