Reputation: 1
I have a Spring Api with two methods: one of them return a List<byte[]> as a JSONArray, and another method that returns a byte[].
When I call Volley multipart request to return a byte[], I can set it on a ImageView.
API
@GetMapping(value = "/return", produces = MediaType.IMAGE_JPEG_VALUE)
public @ResponseBody byte[] getImage() throws IOException {
File myFile = new File(xxxxxxxxxxxxxxxxxxxxxxx);
InputStream input = new FileInputStream(myFile);
System.out.println(input);
return IOUtils.toByteArray(input);
}
APP
public void returnImage(final ImageView im) {
RequestQueue requestQueue = Volley.newRequestQueue(this);
BinaryRequest binaryRequest = new BinaryRequest(0, getString(R.string._url),
new Response.Listener<byte[]>() {
@Override
public void onResponse(byte[] response) {
im.setImageBitmap(BitmapFactory.decodeByteArray(response, 0, response.length));
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}
);
requestQueue.add(binaryRequest);
}
When I call JSONArrayRequest, I cannot get String, convert to byte, and set on a ImageView.
The code on API is basically the same, but with different return.
Exemple return:
[
{
"images": [],
"JSON": {
"XX":XX,
"XX":XX,
"XX":XX,
"XX":XX,
"XX":XX,
"XX":XX,
"XX":XX,
"XX":XX,
}
}
]
APP
JSONArray jsa = jsonArrayResponse.getJSONObject(i).getJSONArray("images");
if(jsa != null){
for (int nbr = 0; nbr < jsa.length(); nbr++) {
byte[] bytes = jsa.get(nbr).toString().getBytes();
ivPhoto.setImageBitmap(BitmapFactory.decodeByteArray(bytes, 0, bytes.length));
return;
}
}
(I receive one image only at moment).
I got the String's return and put on https://codebeautify.org/base64-to-image-converter. The image appears correctly.
Upvotes: 0
Views: 9851
Reputation: 4694
As I understand you receive images in Base64 format. Any characters can be represented as bytes, but it does not mean you can consider it an image. And what is basically happens is that you try to create an image from encoded in Base64 format, while BitmapFactory.decodeByteArray
takes
@param data byte array of compressed image data
You must decode from Base64 to bytes before you decode bytes into the image.
byte[] decodedImageBytes = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(decodedImageBytes, 0, decodedImageBytes.length);
Upvotes: 2