I have a base64 binary string which I got from an image in mongoDB. For example:
[255,216,255,224,0,16,74,70,73,70,0,1,1,1,0,96,0,96,0,0,255,219,0,67,0,8,6,6,7,6,5,8,7,7,7,9,9,8,10,12,20,13,12,11,11,12,25,18,19,15,20,29,26,31,30,29,26,28,28,32,36,46,39,32,34,44,35,28,28,40,55,41,44,48,49,52,52,52,31,39,57,61,56,50,60,46,51,52,50,255,219,0,67,1,9,9,9,12,11,12,24,13,13,24,50,33,28,33,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,.................,253,246,255,0,190,141,20,80,2,249,142,57,222,223,153,160,200,231,146,237,159,173,20,80,1,230,63,247,219,254,250,52,155,223,251,237,255,0,125,26,40,160,4,103,102,108,177,44,79,82,78,73,162,138,40,3,255,217]
In Android, how can I convert this string into a bitmap? This code does not work:
byte[] decodedString = {Base64 Binary Here}.getBytes();
Bitmap bmp = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
This is my full code:
// JSON Parser
JsonParser jsonParser = new JsonParser();
JsonArray jsonArray = (JsonArray) jsonParser.parse(json_result);
String thirdParse = null;
for (int i = 0; i < jsonArray.size(); i++) {
JsonObject object = (JsonObject) jsonArray.get(i);
JsonObject firstParse = (JsonObject) object.get("img");
JsonObject secondParse = (JsonObject) firstParse.get("data");
thirdParse = secondParse.get("data").toString();
}
byte[] decodedString = thirdParse.getBytes();
Bitmap bmp = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
imageView.setImageBitmap(bmp);
This is the JSON I get from mongoDB:
[{"img":{"data":{"type":"Buffer","data":[(base64 binary data)]}}}]
Okay after a bit of diving in, the reason it didn't work is because here
byte[] decodedString = thirdParse.getBytes();
You are not taking the byte array from the string you are actually converting thirdParse into a bytearray so if you get for example thirdparse = [1,2,3] , when you use getBytes() it will convert this array to bytes and what you want is to take the values themselves directly not converting anything so here is what i did
first i created a method that you would give thirdParse to
public byte[] convertToByteArray(String stringContainingByteArray){
String[] l = stringContainingByteArray.replace("[","").replace("]","").split(",");
byte [] byteArray = new byte[l.length];
for (int i=0;i<l.length;i++){
byteArray[i]=Byte.parseByte(l[i]);
}
return byteArray;
}
and you will just send it the thirdParse string and retrieve a byteArray which you will pass to the BitmapFactory as follows
byte[] byteArray = convertToByteArray(stringContainingByteArray)
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
imageView.setImageBitmap(bmp)
for simplicity the whole code without methods will be as follows
// JSON Parser
JsonParser jsonParser = new JsonParser();
JsonArray jsonArray = (JsonArray) jsonParser.parse(json_result);
String thirdParse = null;
for (int i = 0; i < jsonArray.size(); i++) {
JsonObject object = (JsonObject) jsonArray.get(i);
JsonObject firstParse = (JsonObject) object.get("img");
JsonObject secondParse = (JsonObject) firstParse.get("data");
thirdParse = secondParse.get("data").toString();
}
String[] l = thirdParse.replace("[","").replace("]","").split(",");
byte [] decodedString = new byte[l.length];
for (int i=0;i<l.length;i++){
decodedString[i]=Byte.parseByte(l[i]);
}
Bitmap bmp = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
imageView.setImageBitmap(bmp);
I just changed my image saving type from Buffer to String in mongoDB connection, and then changed encoding to base64 String.
My problem is: i'm trying to convert byte[] into image. The byte[] comes from JSON and it's in this format:
"4oCwUE5HDQoaCgAAAA1JSERSAAAAfwAAAFAIBgAAADBHwqrDsAAAAAlwSFlzAAAAJwAAACcBKgnigJhPAAAgAElEQVR4xZPCrMK9ecWSZcOZfcOfw7c5w5vCvW/CqXp..." it goes for another 100 lines.
The code where the problem occurs:
String jsonString = EntityUtils.toString(httpEntity);
// again some simple validation around the returned string
if(jsonString != null && jsonString.length() != 0) // checking string returned from service to grab id
{
JSONArray jsonArray = new JSONArray(jsonString);
for(int i=0; i< jsonArray.length(); i++)
{
HashMap<String, Object> map = new HashMap<String, Object>();
// you need to store the results somewhere and pass it on to the player list
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
int id = jsonObject.getInt("id");
String name = jsonObject.getString("name");
byte[] image = jsonObject.getString("image").getBytes();
String base64 = jsonObject.getString("image");
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
byte[] decodedString = Base64.decode(base64, Base64.DEFAULT);
String images = new String(decodedString);
Bitmap decodedByte = Utils.getBitmapFromString(images);
decodedByte.compress(Bitmap.CompressFormat.PNG, 100, stream);
Log.d("DECODEDBYTE IS: ", decodedByte.toString());
if (decodedByte != null) {
ImageView imgView = (ImageView) findViewById(R.id.image);
imgView.setImageBitmap(decodedByte);
}
} catch (Exception e) {
Log.d("Exception", e.toString());
}
map.put("name", name.toString());
map.put("image", image);
Log.d("JSON OBJECTS:", jsonObject.toString());
Log.d("WHATS IN MAP:", map.toString());
playersList.add(map);
}
Before I was getting NULL value at decodedByte (Bitmap) now it's telling me:
Unable to decode stream: FileNotFoundException.
I'm struggling with this two days already and can't get this working!
Any ideas of what might be wrong?
[EDIT] These are values from the debbuger:
jsonString "[{"id":"16","clubid":"1","name":"Theo
Walcott","password":"0000","image":"4oCwUE5HDQoaCgAAAA1JSERS...WeKAsGfDngAAAABJRU5Ewq5CYOKAmg==","lastupdated":"2013-08-22
09:31:58","isDeleted":"0"}]" (id=830043725448) map HashMap
(id=830043562472) name "Theo Walcott" (id=830043434760)
parameters ArrayList (id=830043725168) arg0 String[0]
(id=830043671992) stream ByteArrayOutputStream (id=830043562528)
decodedString (id=830045128536) images "‰PNG\r\n\n
And the LogCat:
10-30 14:02:57.717: D/JSON OBJECTS:(14452):
{"id":"24","image":"4oCwUE5HDQoaCgA...CFcKpD8WTw5 10-30 14:02:57.717:
D/WHATS IN MAP:(14452): {image=[B#428e6d20, name=Ryo Miyaichi} 10-30
14:03:03.747: E/BitmapFactory(14452): Unable to decode stream:
java.io.FileNotFoundException: /: open failed: EISDIR (Is a directory)
10-30 14:03:03.747: I/System.out(14452): resolveUri failed on bad
bitmap uri
byte[] encodeByte = Base64.decode(base64, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
if(bitmap != null){
ImageView imgView = (ImageView) findViewById(R.id.image);
imgView.setImageBitmap(bitmap);
}
This is how you should decode a String to a Bitmap from the response you get from json.
This is my first question on stackoverflow.
My problem is: i'm trying to convert byte[] into image. The byte[] comes from JSON and it's in this format:
"4oCwUE5HDQoaCgAAAA1JSERSAAAAfwAAAFAIBgAAADBHwqrDsAAAAAlwSFlzAAAAJwAAACcBKgnigJhPAAAgAElEQVR4xZPCrMK9ecWSZcOZfcOfw7c5w5vCvW/CqXp..." it goes for another 100 lines.
The code where the problem occurs:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(PlayersListActivity.URL);
httpPost.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
BufferedHttpEntity bufferedEntity = new BufferedHttpEntity(httpEntity);
// if this is null the web service returned an empty page
if(httpEntity == null) // response is empty so exit out
return null;
String jsonString = EntityUtils.toString(bufferedEntity);
// again some simple validation around the returned string
if(jsonString != null && jsonString.length() != 0) // checking string returned from service to grab id
{
JSONArray jsonArray = new JSONArray(jsonString);
for(int i=0; i< jsonArray.length(); i++)
{
HashMap<String, Object> map = new HashMap<String, Object>();
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
int id = jsonObject.getInt("id");
String name = jsonObject.getString("name");
byte[] images = jsonObject.getString("image").getBytes();
Bitmap btm = BitmapFactory.decodeByteArray(images, 0, images.length);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
btm.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Bitmap btm2 = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
ImageView image = (ImageView) findViewById(R.id.image);
image.setImageBitmap(btm2);
map.put("name", name.toString());
map.put("image", images.toString());
Log.d("JSON OBJECTS:", jsonObject.toString());
Log.d("WHATS IN MAP:", map.toString());
playersList.add(map);
And ofcourse error that I'm getting in LogCat:
SkImageDecoder:: Factory returned null.
java.lang.NullPointerException
and it points out on this line:
Bitmap btm2 = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
I have done reseach but nothing really points on what I'm missing.
Any ideas??
Thanks!!
4oCwUE5HDQoaCgAAAA1JSERSAAAAfwAAAFAIBgAAADBHwqrDsAAAAAlwSFlzAAAAJwAAACcBKgnigJhPAAAgAElEQVR4xZ
PCrMK9ecWSZcOZfcOfw7c5w5vCvW/CqXp..." it goes for another 100 lines.
Its seems like its not a byte[] but its a Base64 String
So try like
String base64 = jsonObject.getString("image");
byte[] decodedString = Base64.decode(base64, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
image.setImageBitmap(decodedByte);
Hope this help you.
**Your web service is the UTF-8 decoder**
String str=[Base64];
str = URLDecoder.decode(str, "UTF-8");
ImageView imgView.setImageBitmap(StringToBitMap(str));
public static Bitmap StringToBitMap(String image) {
try {
byte[] encodeByte = Base64.decode(image.getBytes(), Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0,
encodeByte.length);
return bitmap;
} catch (Exception e) {
e.getMessage();
return null;
}
}
Hi guys I wanted to ask you one thing, I have a chat that transfers strings and I can even attach of JPEG images before sending them to convert it into a string and then decode in BITMAP just that when I decode it crashes the app. I wanted to know if it is the right code to decode it.
NOME = (TextView) row.findViewById(R.id.comment);
NOME.setText(coment.comment);
String a = NOME.getText().toString();
if(a.length() > 1024 )
{
byte[] image = Base64.decode(a, 0);
int lung = a.length();
Bitmap bitmap = BitmapFactory.decodeByteArray(image, 0, lung);
Image = (ImageView) row.findViewById(R.id.image);
Image.setImageBitmap(bitmap);
}
The code looks fine, if I had to guess I would say you're getting the Out of Memory error, which is very common when loading images. Check out
http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
for some best practices when loading images.
The method for Encoding an Image to String Base64 :
public static String encodeToString() {
String imageString = null;
try {
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
imageString = Base64.encodeToString(b, Base64.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
}
return imageString;
}
The method for Decoding String Base64 to Image :
public static void decodeToImage(String imageString) {
try {
byte[] imageByte = Base64.decode(imageString, Base64.DEFAULT);
Bitmap bm = BitmapFactory.decodeByteArray(imageByte, 0, imageByte.length);
image_view.setImageBitmap(bm);
} catch (Exception e) {
e.printStackTrace();
}
}