我有一个非常简单的应用程序,包含一个 ImageView 和一个 Button。我加载的第一个 Drawable 资源图像视图在 XML 布局中用“android:src”标签指定,但是在运行时我想改变它显示的图片。为此,我启动一个活动以从 sd 卡中选取图像(意图发送到 MediaStore.Images.Media.EXTERNAL_CONTENT_URI)。但是,当选择图片时,我尝试使用所选图片的 URI 更新 ImageView,但收到消息“java.lang.OutOfMemoryError:位图大小超出VM预算"
我正在尝试加载我的 HTC-Hero 的相机拍摄的照片(照片大小约为 1.1M),但没有成功,似乎只能处理小于 500KB 的照片。但是我需要加载用相机拍摄的照片。我该如何解决这个问题?我究竟做错了什么。在我看来,代码非常简单并且应该可以工作。
public void onClick(View v){
Intent selectImageIntent=new Intent(Intent.ACTION_PICK ,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(selectImageIntent,1);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==Activity.RESULT_OK){
Uri selectedImageUri = data.getData();
Log.i(TAG,"chosen image: "+selectedImageUri.toString());
ImageView imageView = (ImageView) this.findViewById(R.id.ImageView01);
imageView.setImageURI(selectedImageUri);//here I get the OutOfMemoryError
imageView.invalidate();
}else{
//canceled
}
}
附注这是应用程序应该做的唯一事情,我没有创建其他对象,所以我想指出,除了显示图像之外,我没有将堆空间用于其他东西。
似乎在加载新位图之前我必须回收 ImageView 显示的位图,现在它可以正常工作了。希望这对其他人有帮助,只需在设置新 ImageView 的内容之前调用以下方法即可。
((BitmapDrawable)imageView.getDrawable()).getBitmap().recycle();
所以代码现在看起来像这样:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case INTENT_REQUEST_SELECT_IMAGE:
if(resultCode==Activity.RESULT_OK){
Uri selectedImageUri = data.getData();
Log.i(TAG,"selectedImageUri.getPath()"+selectedImageUri.getPath() );
ImageView imageView = (ImageView) this.findViewById(R.id.ImageView_of_text);
((BitmapDrawable)imageView.getDrawable()).getBitmap().recycle();
imageView.setImageURI(selectedImageUri);
imageView.invalidate();
}else{
//TODO define what to do in case the user canceled OCR or any other event
}
break;
default:
break;
}
}
请注意对ImageView的Bitmap的回收调用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)