我在stackoverflow中遇到了很多关于这个错误的问题,但是他们没有找到解释我方案的正确解决方案。
在我的Android应用程序中,我必须允许用户单击按钮以打开图库并选择图像。然后需要将特定的选定图像加载到我的布局(UI)中的ImageView。
这样做很好。以下是我用来实现此目的的代码。
在上传按钮中,点击 - >
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), REQUEST_UPLOAD_IMG);
然后onActivityResult - >
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
//super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK)
{
if(requestCode==REQUEST_UPLOAD_IMG)
{
Uri selectedImageURI = data.getData();
uploadImgVW.setImageURI(selectedImageURI);
}
else
{
Toast.makeText(MainActivity.this, "You can only select an Image.", Toast.LENGTH_LONG).show();
}
}
}
但是,如果用户选择尺寸较大的图像(如 2MB 大小),应用程序将退出并显示以下错误。但是正常(KB级别)图像非常好,并且想知道我能为此问题做些什么(处理这种错误情况)。感谢...
错误 - >
06-20 16:43:58.445: E/AndroidRuntime(2075): FATAL EXCEPTION: main
06-20 16:43:58.445: E/AndroidRuntime(2075): java.lang.OutOfMemoryError: bitmap size exceeds VM budget
答案 0 :(得分:7)
有一系列文章有效地描述了how to manage the bitmaps。查看代码,加载图像时不知道它有多大,最终会遇到这些问题,尤其是在加载和处理许多图像时。
one of those articles中描述的想法是加载已缩小的位图(首先检查要加载的图像有多大,然后计算缩小因子,然后才会加载缩放的比例下图像)。为此,您需要首先了解ImageView的尺寸,然后您必须使用BitmapFactory.decode(...),因为您要显示目标文件的Uri。提交文件应该是微不足道的。
此外,您还需要检查应用程序的内存消耗情况......您可能还有其他资源挂在内存中,您需要清理它们。我正在使用一个非常有用的工具 - MAT。关于此的一篇非常好的文章可以be found here。作者Patrick Dubroy在Google IO 2011上就此主题举行了一次非常有趣的会议。 Check that out,对我来说这非常有帮助......
答案 1 :(得分:1)
调整图像大小,然后设置
public static Bitmap decodeUri(Context c, Uri uri, final int requiredSize)
throws FileNotFoundException {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(c.getContentResolver().openInputStream(uri), null, o);
int width_tmp = o.outWidth
, height_tmp = o.outHeight;
int scale = 1;
while(true) {
if(width_tmp / 2 < requiredSize || height_tmp / 2 < requiredSize)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(c.getContentResolver().openInputStream(uri), null, o2);
}
或者你可以这样使用
if(resultCode == RESULT_OK){
Uri selectedImage = data.getData();
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(selectedImage);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
profileImage.setImageBitmap(Bitmap.createScaledBitmap(yourSelectedImage , 120, 120, false));
}
答案 2 :(得分:0)
你可以试试这个......
BitmapFactory.Options options = new BitmapFactory.Options();
options.inTempStorage = new byte[16*1024];
Bitmap bitmapImage = BitmapFactory.decodeFile(path, options);