Serialize image to a String

随声附和 提交于 2019-12-24 03:07:26

问题


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!.


回答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.




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/10391170/serialize-image-to-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!