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); //显示图片
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); //显示图片
评论
发表评论