BitmapFactory.decodeStream returns null without exception

I am trying to download a remote image from a server and thanks to a lot of sample code in stackoverflow. I have a solution that works in 2 of 3 images. I really don't know what the problem is with the third image, and sometimes when the code runs in the debugger, loading the image. Also, if I upload a problem image first, the other two images sometimes do not load.

Here is the code:

public static Drawable getPictureFromURL(Context ctx, String url, final int REQUIRED_SIZE) throws NullPointerException { //Decode image size BitmapFactory.Options o = new BitmapFactory.Options(); int scale = 1; if (o.outWidth > REQUIRED_SIZE) { scale = (int) Math.pow(2, (int) Math.round(Math.log(REQUIRED_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5))); } Log.i(Prototype.TAG, "scale: "+scale); //Decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; Bitmap bmp; try { bmp = BitmapFactory.decodeStream((InputStream) Tools.fetch(url), null, o2); if(bmp!=null) return new BitmapDrawable(ctx.getResources(), bmp); else return null; } catch (Exception e) { Log.e(Prototype.TAG, "Exception while decoding stream", e); return null; } } 

During debugging, I found that o.outWidth is -1, which indicates an error, but an Exception is not thrown, so I can’t say what went wrong. An InputStream always returned a valid value, and I know that the image exists on the server.

Best regards, Daniel

+8
android bitmapfactory
source share
1 answer

I found the answer here and updated the fetch method:

 private static InputStream fetch(String address) throws MalformedURLException,IOException { HttpGet httpRequest = new HttpGet(URI.create(address) ); HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = (HttpResponse) httpclient.execute(httpRequest); HttpEntity entity = response.getEntity(); BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity); InputStream instream = bufHttpEntity.getContent(); return instream; } 
+16
source share

Source: https://habr.com/ru/post/650043/


All Articles