2

Good friends of the forum.

I've been searching a lot, and I could not find how to serialize an image and pass it to a String in android.

as might be not so, If someone knows and wants to inform me I would appreciate very much!.

JulioStyle88
  • 95
  • 1
  • 9

3 Answers3

1

Although the java.awt.Image class is not (does not implement) java.io.Serializable, javax.swing.ImageIcon is. Because of this, you can serialize it as follows:

ImageIcon myImage; // declare somewhere
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(myImage);
byte[] theBytes = baos.toByteArray();
StringBuffer buf = new StringBuffer();
for (byte b : theBytes) {
  buf.append((char) b); // cast to char, then append
}
String theString = b.toString();

I'll let you figure out how to reverse it, but here's a hint: instead of OutputStream classes, use InputStream classes.

wchargin
  • 14,264
  • 11
  • 61
  • 106
1

You could read the bytes of the image to a byte[] and then encode the byte[] using Base64, Here is how.

Community
  • 1
  • 1
Óscar López
  • 215,818
  • 33
  • 288
  • 367
1

Base64 will be the most efficient way to reliably transfer binary data (such as an image) in a string.

However, since you are requesting something smaller, you may consider base64 encoding your image, then compressing the resultant string, then base64 encoding that...

It saves you a few bytes, but not many. And in some cases it may even make the result larger.

If you have control of both the server and the client, you should consider creating another interface that would allow you to send bytes.

Lunchbox
  • 1,376
  • 8
  • 13