How to get the image from parsed JSON into ListView - android

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.

Related

How to convert base64 binary to bitmap in 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.

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

Error in BitmapFactory.decodeByteArray

Hello
I have the following issue, i'm trying to retrieve the image from openweathermap.com, I have a service that access to the the page and retrieve the image as a byte array, I'm using the same service in an IOS app and work fine so I know that the service is working properly.
Service Code:
public byte[] GetWeatherIcon(string iconDesc)
{
byte[] result;
string url = "http://openweathermap.org/img/w/" + iconDesc + ".png";
Image image = RequestImage_Get(url, null, null, null);
System.Drawing.Imaging.ImageFormat format = System.Drawing.Imaging.ImageFormat.Png;
using (var ms = new MemoryStream())
{
image.Save(ms, format);
result = ms.ToArray();
}
return result;
}
In my Android application I'm executing the following code to access the service:
String urlIcon = SERVICEURL + "/GetWeatherIcon/" + weather.getWeather().get(0).getIcon();
InputStream iconStream = ExecuteRequestService(urlIcon);
BufferedReader rdIcon = new BufferedReader(new InputStreamReader(iconStream));
String jsonIcon = rdIcon.readLine();
JSONObject objIcon = new JSONObject(jsonIcon);
byte[] bytes = objIcon.getString("GetWeatherIconResult").getBytes("UTF-8");
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
weather.setImage(bmp);
The method ExecuteRequestService code's is:
protected InputStream ExecuteRequestService(String url) throws Exception{
try{
URL urlObj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
if(conn.getResponseCode() == 200) {
return conn.getInputStream();
}else {
return null;
}
}catch (Exception ex){
throw new Exception("An error occurred accessing MiOS server");
}
}
The error that i'm getting is: D/skia: --- SkImageDecoder::Factory returned null
I was reading a few post with the same exception but all of them are related with BitmapFactory.decodeStream but in my case is different as you can see but i can't find the problem, that's why i need your help
Here is an example of the url that I'm running so you can see the Json:Url running to get Json
Thanks in advanced
SkImageDecoder::Factory returned null ? You mean BitmapFactory.decodeByteArray() returns null ? Same cause as allways. Not enough memory. What's the size of the byte array? What's the size of the picture?
As private variable in your AsyncTask class:
Bitmap bmp = null;
In doinbackground:
JSONObject objIcon = new JSONObject(jsonIcon);
String thevalues = objIcon.get("GetWeatherIconResult").toString();
thevalues = thevalues.replace("[", "");
thevalues = thevalues.replace("]", "");
result = thevalues;
String values[] = thevalues.split(",");
byte bytes[] = new byte [values.length];
int nr = -1;
while (++nr < values.length)
{
int value = Integer.valueOf(values[nr]);
bytes[nr] = (byte)value;
}
bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
In onPostExecute:
if ( bmp != null )
{
ImageView imageView = (ImageView)MainActivity.this.findViewById ( R.id.imageView);
imageView.setImageBitmap(bmp);
}
Thank you so much for all your help, after break my neurons y found a good solution for this:
As you can see the structure of the json I was getting the byte array as String this is the code with the solution:
String urlIcon = SERVICEURL + "/GetWeatherIcon/" + weather.getWeather().get(0).getIcon();
InputStream iconStream = ExecuteRequestService(urlIcon);
BufferedReader rdIcon = new BufferedReader(new InputStreamReader(iconStream));
String jsonIcon = rdIcon.readLine();
JSONObject objIcon = new JSONObject(jsonIcon);
JSONArray jsonArray = objIcon.getJSONArray("GetWeatherIconResult");
byte[] bytes = new byte[jsonArray.length()];
for(int i=0; i<jsonArray.length(); i++){
bytes[i] = (byte) jsonArray.getLong(i);
}
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
weather.setImage(bmp);
I hope this help a few more like me.
simply use below code
byte[] img = Base64.decode(Service.GetImage(), Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(img, 0, img.length);
imageid.setImageBitmap(getCircleBitmap(bitmap));

how to upload image in base64 on server

i have a problem, i am uploading image on server but it is not. i have convert image in base64 and get through json. but json is not properly closed due to this i m getting error. error id om postimafe variable. in this variable {"key"""encode, here is json is not closed.
// code for convert base64
public static String getBase64String(String baseFileUri)
{
String encodedImageData = "";
try
{
System.out.println("getBase64String method is called :" +baseFileUri);
Bitmap bm = BitmapFactory.decodeFile(baseFileUri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
encodedImageData = Base64.encodeToString(b, Base64.DEFAULT);
//ArrayList<NameValuePair> imagearraylistvalue = new ArrayList<NameValuePair>();
//imagearraylistvalue.add(new BasicNameValuePair("image", encodedImage));
System.out.println("encode data in upload file :" +encodedImageData );
}
catch(Exception ex)
{
System.out.println("Exception in getBase64String method in Utility class :" +ex);
}
return encodedImageData ;
}
// code for json and uplod base64 to server but i m getting error
System.out.println("fullupload image for 1:" +fulluploadimgpath);
String base64String = Utility.getBase64String(fulluploadimgpath);
System.out.println("base64String is in :" +base64String);
if (base64String != null)
{
JSONObject postImageData = new JSONObject();
postImageData.put("media",base64String);
System.out.println("post image :" +postImageData);
HttpResponse imgPostResponse = Utility.postDataOnUrl(Utility.getBaseUrl()+"user/upload",obj.toString());
System.out.println("fullupload image for imgPostResponse:" +imgPostResponse);
if (imgPostResponse != null)
{
String imgResponse = Utility.readUrlResponseAsString(imgPostResponse);
System.out.println("imgResponse is in imgResponse :" +imgResponse);
if (imgResponse != null|| imgResponse.trim().length() != 0)
{
JSONObject jResObj = new JSONObject();
if (jResObj.getBoolean("rc"))
{
obj.put(hidobj.getReceiveAs(),jResObj.getLong("ident"));
}
}
String encodedImageData =getEncoded64ImageStringFromBitmap(your bitmap);
public String getEncoded64ImageStringFromBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 70, stream);
byte[] byteFormat = stream.toByteArray();
// get the base 64 string
String imgString = Base64.encodeToString(byteFormat, Base64.NO_WRAP);
return imgString;
}

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