gpt4 book ai didi

android - 更改 ImageView 内容会导致 OutOfMemoryError

转载 作者:IT老高 更新时间:2023-10-28 23:08:52 26 4
gpt4 key购买 nike

我有一个非常简单的应用程序,只有一个 ImageView 和一个 Button。我的ImageView 加载的第一个Drawable 资源是用XML 布局中的“android:src”标签指定的,但是在运行时我想更改它显示的图片。为此,我启动了一个 Activity 以从 sd 卡中选择图像( Intent 发送到 MediaStore.Images.Media.EXTERNAL_CONTENT_URI)。 However when the picture is selected, i try to update the ImageView with the chosen Picture's URI but i get the message "java.lang.OutOfMemoryError: bitmap size exceeds VM budget"

我正在尝试加载用我的 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上的recycle调用。

关于android - 更改 ImageView 内容会导致 OutOfMemoryError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2191407/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com