Send image as json entry android

*爱你&永不变心* 提交于 2019-12-12 07:42:45

问题


I have a requirement where, i am sending a json file to the server and the parsing happens at the server side. I have created the entries to the json file, now i want to store an image stored in imageview as an entry to the json file. Searched several previous posts but could not find exactly what to do. Any pointers would be of great help for storing the image in json format for sending through server.


回答1:


If you want to include Image in a JSON object which you will be sending in a request, convert Image into Base64 string and put this string into the JSON object.

For example:

String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);

Check:

  • How to convert a image into Base64 string?
  • Convert png or jpg image to Base64 string in Android



回答2:


Well, it's kind of experimental, but you can create an array of bytes out of the bitmap, and then create a new string with that array of bytes, and then send it to the server.

However, why don't you just send a POST request to save the image directly, without any experimental processing or parsing?




回答3:


Try base64-encoding the image (like below, where the Uri is your Image - but beware: ImageView has no Getter for the ImageUri, so you have to store it by yourself!):

Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);

ContentResolver cr = getContentResolver();
InputStream is = cr.openInputStream(uri);

byte[] data = getBytesFromFile(is);

byte[] encoded_data = Base64.encodeBase64(data);
data_string = new String(encoded_data);

Now you have an base64-encoded String data_string that you can send with your JSON request. On the server-side you just have to decode the String and save the picture.



来源:https://stackoverflow.com/questions/15565928/send-image-as-json-entry-android

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