给定图像 url,我需要下载它并在 ImageView 中显示。
一切正常,除了图像很大并且抛出 OutOfMemoryException的情况。
希望 Android 文档可以解决这个问题:http: //developer.android.com/training/displaying-bitmaps/load-bitmap.html
我试图调整这段代码以接受 InputStream,而不是 Resource。
但是,似乎我在那里遗漏了一些东西,因为没有显示图像,也不例外,但是我在 LogCat 中看到了这个:SkImageDecoder::Factory returned null
以下是我如何解码图像并将其缩小(基于 Android 文档):
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;
}
现在,在我的位图下载器方法中,我这样称呼它:
inputStream=entity.getContent();
return decodeBitmapFromInputStream(inputStream, 320, 480);
这是完整的方法,以防万一:
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;
}