Android载入图片时Out of Memory

嗯,这个经典的问题也被我遇上了,修改代码如下:

imageView = (ImageView) findViewById(R.id.imageview);

InputStream is = this.getResources().openRawResource(R.raw.idcard);

BitmapFactory.Options option = new BitmapFactory.Options();
options.inJustDecodeBounds = true;  //先设为只取图片的宽高不实际载入图片
Bitmap btp = BitmapFactory.decodeStream(is, null, options);
int imageWidth = options.outWidth;
int imageHeight = options.outHeight;
DisplayMetrics dm = getReources().getDisplayMetrics(); //获取屏幕的分辨率
int screenHeight = dm.heightPixels;
int screenWidth = dm.widthPixels;
double heightRate = Math.ceil( (double)imageHeight / (double)screenHeight );
double widthRate = Math.ceil( (dobule)imageWidth / (double)screenWidth );
int shrinkRate = 0;
if (heightRate > widthRate) {shrinkRate = (int) heightRate;}
else { shrinkRate = (int) widthRate; }
if (shrinkRate % 2 == 1 ) {shrinkRate += 1;}  //缩放比例需为2的倍数

options.inJustDecodeBounds= false; //重新设置参数为不获取宽高
options.imSampleSize = shrinkRate; //设置载入图片时的缩放比例
btp = BitmapFactory.decodeStream(is, null, options);

imageView.setImageBitmap(btp);   //显示图片

评论

此博客中的热门博文

Windows上调试C/C++程序时自动产生coredump的设置方法

利用Gitlab的Jira issue tracker实现Jira issue自动根据Gitlab commit/merge更新状态

go用xorm去update数据库的一个坑