我在编码图像以将其发送到json文件时遇到问题。如果我将图像字符串提取为txt并进行解码,则可以正常工作,并且可以看到编码后的图像,但是当我将其放入json文件时,当图像字符串遇到“ /”时,图像字符串会发生变化,它将转换为“ \ / ”添加到json文件,如果imagestring更改行,则json文件添加“ \ n”。这样就无法从json文件中提取图像字符串,以便查看图像。
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
Bitmap bitmap2 = ((BitmapDrawable) secondImageV.getDrawable()).getBitmap();
bitmap2.compress(Bitmap.CompressFormat.JPEG, 100, baos2);
byte[] imageBytes2 = baos2.toByteArray();
imageString2 = Base64.encodeToString(imageBytes2, Base64.DEFAULT);
sendPost(imageString1,imageString2,sendAlert);
public void sendPost(String im1, String im2, String alert) {
JSONObject json = new JSONObject();
try {
json.put("name", compname.getText());
json.put("hydrovalue", _hydrometerValue.getText());
json.put("im1", im1) ;
json.put("im2", im2);
json.put("hydrohealth", check1);
json.put("hydrorepair", check2);
json.put("hydroalert", alert);
json.put("stime", stime.getText());
json.put("etime", etime.getText());
json.put("comm", _comments.getText());
} catch (JSONException e) {
e.printStackTrace();
}
String url = "https://api.myjson.com/bins/lmz8i";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, json,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(), "String Response : " + response.toString(), Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Error getting response", Toast.LENGTH_LONG).show();
}
});
最佳答案
使用Base64“ URL安全”编码。实例化这些编码器/解码器,如下所示:java.util.Base64.getUrlEncoder和java.util.Base64.getUrlDecoder
关于java - 将图像转换为json文件中的Base64问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58937405/