Given the image url, I need to download it and display in an ImageView.
Everything works fine, except the situation when the images are quite large, and an OutOfMemoryException is thrown.
Hopefully, Android documentation provides a solution to this problem: http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
I tried to adapt that snipped of code to accept an InputStream, instead of a Resource.
However, it seems I am missing something there, because the image is not displayed, no exception, but I see in the LogCat this: SkImageDecoder::Factory returned null
Here is how I decode the image and scale it down (based on Android documentation):
public static Bitmap decodeBitmapFromInputStream(InputStream inputStream,
int reqWidth, int reqHeight) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(inputStream, null, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeStream(inputStream, null, options);
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
}
return inSampleSize;
}
Now, in my bitmap downloader method, I call it like this:
inputStream=entity.getContent();
return decodeBitmapFromInputStream(inputStream, 320, 480);
Here’s the full method, just in case:
static Bitmap downloadBitmap(String url){
AndroidHttpClient client=AndroidHttpClient.newInstance("Android");
HttpGet getRequest=new HttpGet(url);
try{
HttpResponse response=client.execute(getRequest);
int statusCode=response.getStatusLine().getStatusCode();
if(statusCode!=HttpStatus.SC_OK){
Log.d("GREC", "Error "+statusCode+" while retrieving bitmap from "+url);
return null;
}
HttpEntity entity=response.getEntity();
if(entity!=null){
InputStream inputStream=null;
try{
inputStream=entity.getContent();
return decodeBitmapFromInputStream(inputStream, 320, 480);
}catch (Exception e) {
Log.d("GREC", "Exception occured in BitmapDownloader");
e.printStackTrace();
}
finally{
if(inputStream!=null){
inputStream.close();
}
entity.consumeContent();
}
}
}catch (Exception e) {
getRequest.abort();
Log.d("GREC", "Error while retriving bitmap from "+url+", "+e.toString());
}finally{
if(client!=null){
client.close();
}
}
return null;
}
The problem was that once you’ve used an InputStream from a HttpUrlConnection, you can’t rewind and use the same InputStream again. Therefore you have to create a new InputStream for the actual sampling of the image. Otherwise we have to abort the http request.
see decodeStream returns null