鉴于图片网址,我需要下载并在ImageView中显示 一切正常,除了图像非常大的情况,并且抛出 OutOfMemoryException 。
希望Android文档提供此问题的解决方案:http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
我尝试调整剪切的代码来接受InputStream,而不是资源 但是,似乎我在那里遗漏了一些东西,因为图像没有显示,也没有异常,但我在LogCat中看到: SkImageDecoder :: Factory返回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;
}
答案 0 :(得分:0)
问题在于,一旦您使用了来自HttpUrlConnection的InputStream,就无法再次回放并再次使用相同的InputStream。因此,您必须为图像的实际采样创建新的InputStream。否则我们必须中止http请求。 见decodeStream returns null