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));
Related
I have the code for downloading image from URL to SDCard, but my device can set up the image ONLY from bitmap.
The question is how I can consume image from URL directly into SQLite Database and then retreive it as the bitmap?
Thanks for any help
public void getNewLogoFromURL(String logo) throws IOException {
new GetLogo().execute(logo);
}
class GetLogoForReceipt extends AsyncTask <String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
try {
downloadFile(params[0]);
} catch ( IOException e ) {
}
return null;
}
}
public void downloadFile(String url) throws IOException {
DataOutputStream fos = null;
try {
File dest_file = new File("/sdcard/Pictures/applicationLogo.png");
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
fos = new DataOutputStream(new FileOutputStream(dest_file));
fos.write(buffer);
fos.flush();
} finally {
fos.close();
}
}
//Device image settingUp code
String[] fileList = { "applicationLogo.png" };
Bitmap[] bitmap = new Bitmap[fileList.length];
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap2 = BitmapFactory.decodeFile("/sdcard/Pictures/applicationLogo.png", options);
for ( int i = 0; i < fileList.length; i++ ) {
bitmap[i] = bitmap2;
}
int ret;
printer = new LinePrinter();
ret = printer.open(device);
ret = printer.setBitmap(bitmap);
Storing bitmaps/images in sqlite database is a bad idea. Download the image to the sd card and save the location in the data base and retrieve the image from sd card when you required.
The below code shows getting bitmap from sdcard.
public Bitmap createBitMap(String path){
File file = new File(path);
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
return bitmap;
}
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;
}
}
I was wondering how i set a buttons background image from a URL on android.
The buttons id is blue if you need to know that.
I tried this but it didn't work.
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
I used the next code for obtain the bitmap, one important thing is sometimes you can't obtain the InputStream, and that is null, I make 3 attemps if that happens.
public Bitmap generateBitmap(String url){
bitmap_picture = null;
int intentos = 0;
boolean exception = true;
while((exception) && (intentos < 3)){
try {
URL imageURL = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageURL.openConnection();
conn.connect();
InputStream bitIs = conn.getInputStream();
if(bitIs != null){
bitmap_picture = BitmapFactory.decodeStream(bitIs);
exception = false;
}else{
Log.e("InputStream", "Viene null");
}
} catch (MalformedURLException e) {
e.printStackTrace();
exception = true;
} catch (IOException e) {
e.printStackTrace();
exception = true;
}
intentos++;
}
return bitmap_picture;
}
Don't load the image directly in the UI (main) thread, for it will make the UI freeze while the image is being loaded. Do it in a separate thread instead, for example using an AsyncTask. The AsyncTask will let the image load in its doInBackground() method and then it can be set as the button background image in the onPostExecute() method. See this answer: https://stackoverflow.com/a/10868126/2241463
Try this code:
Bitmap bmpbtn = loadBitmap(yoururl);
button1.setImageBitmap(bmpbtn);
Dear all I am using below code to download the picture in android,
Where _in is as Input Stream and DataInputStream _din .
I use one URL to download the picture.but sometimes it returning me picture and sometimes it not showing null in bitmap.I have one question here, one is this good way to download picture or suggestion what can be wrong in this picture that same code sometimes returning picture and sometimes it not working ?
if (_in == null) {
_in = urlConnection.getInputStream();
}
if (_din == null) {
_din = new DataInputStream(_in);
}
byte[] data = new byte[0];
byte[] buffer = new byte[512];
int bytesRead;
while ((bytesRead = _din.read(buffer)) > 0) {
byte[] newData = new byte[data.length + bytesRead];
System.arraycopy(data, 0, newData, 0, data.length);
System.arraycopy(buffer, 0, newData, data.length, bytesRead);
data = newData;
}
InputStream is = new ByteArrayInputStream(data);
Bitmap bmp = BitmapFactory.decodeStream(is);
Try this and tell me whether you problem still occurs.
Bitmap ret;
HttpURLConnection conn = null;
try
{
URL u = new URL(mUrl);
conn = (HttpURLConnection) u.openConnection();
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setReadTimeout(CONNECTION_TIMEOUT);
conn.setDoInput(true);
conn.setRequestMethod("GET");
int httpCode = conn.getResponseCode();
if (httpCode == HttpURLConnection.HTTP_OK || httpCode == HttpURLConnection.HTTP_CREATED)
{
InputStream is = new BufferedInputStream(conn.getInputStream());
ret = BitmapFactory.decodeStream(is);
}
else
{
ret = null;
}
}
catch (Exception ex)
{
ret = null;
}
finally
{
if (conn != null)
{
conn.disconnect();
}
}
Why do you use a temp buffer for your image InputStream? Just use the UrlConnection InputStream directly with the BitmapFactory:
_in = urlConnection.getInputStream();
Bitmap bmp = BitmapFactory.decodeStream(_in);
This should always work if your images are ok.