问题
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