我使用手机相机拍摄照片,然后将其设置为我的imageview。我收到内存不足错误,所以我决定使用以下代码来压缩我的位图。错误已经消失,但我的位图也是如此。我的imageview没有显示任何内容。我究竟做错了什么。以下代码位于我的onActivityResult中。
InputStream input = getContentResolver().openInputStream(
data.getData());
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(input,null,o);
//The new size we want to scale to
final int REQUIRED_SIZE=40;
//Find the correct scale value. It should be the power of 2.
int scale=16;
while(o.outWidth/scale/2>=REQUIRED_SIZE && o.outHeight/scale/2>=REQUIRED_SIZE)
scale*=2;
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
bitmap=BitmapFactory.decodeStream(input, null, o2);
firstImageButton.setImageBitmap(bitmap);
答案 0 :(得分:2)
我刚刚完成了类似的例程。我发现我需要关闭然后在对decodeStream的两次调用之间重新打开我的输入流,否则它不会重新定位到流的开头。
对于第二次调用decodeStream,您不需要使用新的BitmapFactory.options,只需将o.inJustDecodeBounds设置为false,并将o.inSampleSize = scale设置为使用它而不是o2。
InputStream input = getContentResolver().openInputStream(data.getData());
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(input,null,o);
input.close();
//The new size we want to scale to
final int REQUIRED_SIZE=40;
//Find the correct scale value. It should be the power of 2.
int scale=16;
while(o.outWidth/scale/2>=REQUIRED_SIZE && o.outHeight/scale/2>=REQUIRED_SIZE)
scale*=2;
//Decode with inSampleSize
input = getContentResolver().openInputStream(data.getData());
o.inJustDecodeBounds=false;
o.inSampleSize=scale;
Bitmap bitmap=BitmapFactory.decodeStream(input, null, o);
firstImageButton.setImageBitmap(bitmap);