6

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.

Donut
  • 110,061
  • 20
  • 134
  • 146
Adham
  • 63,550
  • 98
  • 229
  • 344
  • 4
    What have you tried so far? Which of these steps is causing you the most trouble? – Oliver Charlesworth Feb 22 '11 at 21:15
  • If you tell us why then people may consider suggesting alternatives, as maybe this isn't really the solution to the problem - you could be more elaborate, though. – Grant Thomas Feb 22 '11 at 21:16
  • These two links can help you - http://stackoverflow.com/questions/3211156/how-to-convert-image-to-byte-array-in-java and http://stackoverflow.com/questions/1580038/byte-array-to-image-file – CoolBeans Feb 22 '11 at 21:17
  • Another link that can help http://stackoverflow.com/questions/469695/decode-base64-data-in-java – The Scrum Meister Feb 22 '11 at 21:19
  • @ Oli Charlesworth image to bytearray and vice versa – Adham Feb 22 '11 at 21:19
  • Why do you want to make the byte array into a `String`? Image data is not character data and won't work well as a `String` directly, though using some encoding like Base64 will work. – ColinD Feb 22 '11 at 21:30

1 Answers1

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

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • http://www.programcreek.com/2009/02/java-convert-image-to-byte-array-convert-byte-array-to-image/ like this ? but i'm using jdk 6 but i can't find the class ImageIO !! – Adham Feb 22 '11 at 21:23
  • @adham - `javax.imageio.ImageIO`. Use an IDE to organize your imports, it would find it immediately. – Bozho Feb 22 '11 at 21:24
  • @adham - yes, exactly like shown in the link. Just don't use the `com.sun..internal` - get apache commons-codec. – Bozho Feb 22 '11 at 21:25
  • @adham - did you import it.. ? – Bozho Feb 22 '11 at 21:42