How to convert base64 binary to bitmap in android? - android

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.

Related

Bytes Array is not Converting to Bitmap

Here is the image of response
When Services Giving the reposes of imges into bytes
bitmap is not converting bytes array
jsonObject= response.getJSONObject("dCafeMenuDisplayMainModel");
jsonArray = jsonObject.getJSONArray("cafeMenuDayList");
for (int i=0; i<jsonArray.length();i++){
JSONObject jsonObjectInner = jsonArray.getJSONObject(i);
//list.add(new cafe_menu("Hellow","Yo Man",""));
String title = jsonObjectInner.getString("cafeMenuTitle");
String bytes = jsonObjectInner.getString("cafeMenuImage");
byte[] data = bytes.getBytes();
Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);

How do I load an image in android

How do I load an image from my database to my android application and put it in a listview. The database is MySQL and the image is stored in png format
Here is my codes for retrieving data in my database. The a_emblem is the imageview and the image in my json file
private void showResult() {
JSONObject jsonObject;
ArrayList<HashMap<String, String>> list = new ArrayList<>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY1);
for (int i = 0; i < result.length(); i++) {
JSONObject jo = result.getJSONObject(i);
String a_shortcut = jo.getString(Config.TAG_a_shortcut);
String a_emblem = jo.getString(Config.TAG_a_emblem);
String gold = jo.getString(Config.TAG_gold);
String silver = jo.getString(Config.TAG_silver);
String bronze = jo.getString(Config.TAG_bronze);
String total = jo.getString(Config.TAG_total);
HashMap<String, String> match = new HashMap<>();
match.put(Config.TAG_a_shortcut, a_shortcut);
match.put(Config.TAG_a_emblem, a_emblem);
match.put(Config.TAG_gold, gold);
match.put(Config.TAG_silver, silver);
match.put(Config.TAG_bronze, bronze);
match.put(Config.TAG_total, total);
list.add(match);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(
getActivity(), list, R.layout.standlayout,
new String[]{Config.TAG_a_shortcut, Config.TAG_a_emblem, Config.TAG_gold, Config.TAG_silver, Config.TAG_bronze, Config.TAG_total},
new int[]{R.id.shortcut, R.id.img, R.id.gold, R.id.silver, R.id.bronze, R.id.total});
lv.setAdapter(adapter);
}
use Picasso or glide here is the url for you
Picasso
or
Glide
Here is what you can do.
Convert your image to a bitmap.
Convert your image to a base64 string and save this base64 string in the database.
Convert the base64 string back to the image while using it in the adapter.
Set bitmap in ImageView.
It should definitely work. Code for reference
Convert drawable to Bitmap
Bitmap icon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.icon_resource);
Use the following method to convert a bitmap to a byte array:
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
to encode a base64 string from a byte array:
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
save encoded in the database.
Convert the base64 string back to Bitmap:
byte[] decodedString = Base64.decode(encoded , Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
Set the bitmap to the image view:
imageView.setImageBitmap(bitmap);

compress a bitmap and save it to a bitmap object

I am a beginner in android. I decoded a Base64 image to Bitmap and i need to compress it to to an Outputstream, now i need to use the Bitmap get added to the ArrayList.
try {
// Getting JSON Array from URL
details = json.getJSONArray(TAG_Root);
for(int i = 0; i < details.length(); i++){
JSONObject c = details.getJSONObject(i);
//Storing JSON item in a Variable
String branch = c.getString(TAG_Branch);
String address = c.getString(TAG_Add);
String uname = c.getString(TAG_User);
String photo = c.getString(TAG_Photo);
System.out.println(photo);
//decoding and compressing bitmap
byte[] imageAsBytes = Base64.decode(photo, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
//bitmap = BitmapFactory.decodeStream(getAssets().open("1024x768.jpg"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
//Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
al_branch.add(branch);
al_add.add(address);
al_user.add(uname);
al_photo.add(bitmap);
}
System.out.println(al_branch);
System.out.println(al_photo);
custom_list adapter = new custom_list(MainActivity.this, al_branch,al_user,al_add ,al_photo);

How to get the image from parsed JSON into ListView

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.

How to display image in imageView from byte[], BitmapFactory.decodeByteArray returns null

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;
}
}

Categories

Resources