4
I’m developing an app where I need to convert an image to JSON and send it to a Webservice. Later I will need to perform the reverse path, IE, receive a JSON image of a Webservice to present it to the application user.
Well, to send the image I’m using the following code:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] imgByteArray = stream.toByteArray();
String imgArray = Base64.encodeToString(imgByteArray, Base64.DEFAULT);
JSONObject jsonImg = new JSONObject().put("imgByteArray", imgArray);
So far, so good.
To receive the image I am using the following code:
JSONObject response = new JSONObject(responseJSON);
String imgBytes = responsegetString("imagem");
byte[] imgRecebida = Base64.decode(imgBytes, Base64.DEFAULT);
Bitmap bitNew = BitmapFactory.decodeByteArray(imgRecebida, 0, imgRecebida.length);
However, the answer I have in the logcat is:
java.lang.IllegalArgumentException: bad base-64
What if I change Base64.Code to:
final byte[] imgRecebida = Base64.decode(imgBytes.getBytes(), Base64.DEFAULT);
I receive as a result:
D/skia﹕ --- SkImageDecoder::Factory returned null
Does anyone know why?
It seems that the problem lies in how these bytes are being sent to you. You can send this string to a log, and forward it here, via Pastebin, for example?
– carlosrafaelgn
Maybe this article will help you with the crypt. http://stackoverflow.com/questions/13066762/illegalargumentexception-bad-base-64-while-trying-to-use-base64-on-android-1
– Marcelo Aymone
I found the bug. By receiving the image on Webservice I was saving directly as byte[]. When he returned and tried to use Factory he did not recognize that byte array or give an error in Decode. What I did was save the image as a string right on the server and then return it. I don’t know if this is the right way to go, but it worked. If anyone has a better solution, please let me know. .
– Andrei Maxwel
Hi @Andreimaxwel! To forward raw bytes from side to side using JSON, you can choose to use array notation
[1, 123, 76 ... ]
or use Base64 encoding. With Base64 there is a 33% increase, that is, 3 bytes saw 4 characters. If you convert bytes to array notation, the increase would be much higher, so it’s not worth it, since the Base64 algorithm is fast. Now, since you found the answer yourself, it would be nice if you publish it here, so that other people can learn it too ;)– carlosrafaelgn
Hello Andrei, about the correct form of image storage is its even native form, pure array of bytes. Saving the image in a Base64 string has its advantages and disadvantages, the advantage is that you can use it directly in html without having to do a conversion, a disadvantage is the high storage consumption, try also send this image over the network without performing any conversion, it is faster.
– Leonardo Bosquett