问大家一个问题,你们在工作中服务器传过来的图片是经过经过压缩的吗?面试的时候,被问到,如果服务器传来的图片很大,很容易就OOM了,怎么能解决?
回来查看代码,如果使用BitmapFactory.decodeStream从网络返回的是bitmap对象,已经存在到内存中,如果图片很大,在gridview的场景下,一个滑动操作就OOM了,大家说一下,工作中是怎么做的啊,感谢
先options.inJustDecodeBounds = true,然后计算option的insamplesize赋给option,然后再options.inJustDecodeBounds = false,再生成bitmap对象
bitmap = BitmapFactory.decodeStream(con.getInputStream());这个方法也能传个option,第一次调用的时候,去拿宽和高,设置faslse
private Bitmap createThumbnail(String filepath,int newWidth,int newHeight){
BitmapFactory.Options options=new BitmapFactory.Options();
//第一次采样:仅仅得到原图的宽度和高度,从而获取缩放比例
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filepath,options);
int originalWidth = options.outWidth;
int originalHeight = options.outHeight;
int ratioWidth = originalWidth / newWidth;
int ratioHeight = originalHeight /newHeight;
//缩放比例(取值大)
options.inSampleSize = (ratioWidth > ratioHeight) ? ratioWidth:ratioHeight;
//第二次采样:为了获取缩放后图片的所有像素点
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filepath,options);
}