I'd like to include an image in json and save it.

Asked 2 years ago, Updated 2 years ago, 28 views

public void EnollmentUser() {

    JSONObject mDataJO = new JSONObject();

    String adress = etmapname.getText().toString();
    String adress_descript = etadress.getText().toString();
    String roomInfo = etroomInfo.getText().toString();
    String described = etdescribed.getText().toString();
    int deposit = Integer.parseInt(etPrice.getText().toString());
    int monthly_rent = Integer.parseInt(etmonthly_rent.getText().toString());
    int acreage = Integer.parseInt(etacreage.getText().toString());

    try {
        mDataJO.put("adress",adress);
        mDataJO.put("adress_descript",adress_descript);
        mDataJO.put("deposit",deposit);
        mDataJO.put("roomInfo",roomInfo);
        mDataJO.put("described",described);
        mDataJO.put("monthly_rent",monthly_rent);
        mDataJO.put("acreage",acreage);
        Log.e("dh","server req:\n"+mDataJO.toString());
    } } catch (JSONException e) {
        e.printStackTrace();
    }

I'm a student who just learned Android. I'm studying while looking for Json. I want to input the image like the value of the code. How do I write and write an image like a code?

android

2022-09-22 20:57

1 Answers

Image transfer can be done by converting the image into an array of bytes, encoding this data into a Base64 string, and then forwarding it to JSON's value. (It's a little complicated, but I think it would be easier to understand if you look at the code below.)

Please refer to the function below for the related code. (Application - http://stackoverflow.com/a/30824334/3275152 )

private String getStringFromBitmap(Bitmap bitmapPicture) {
    String encodedImage;
    ByteArrayOutputStream byteArrayBitmapStream = new ByteArrayOutputStream();
    bitmapPicture.compress(Bitmap.CompressFormat.PNG, 100, byteArrayBitmapStream);
    byte[] b = byteArrayBitmapStream.toByteArray();
    encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
    return encodedImage;
}  

Use the string returned from the above function as mDataJO.put("address", address);. If you look at the stack overflow left as a link, there is also a reverse conversion method, so check it out if you need it.


2022-09-22 20:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.