在我的应用程序中,我正在开始使用标准相机应用程序拍照的相机。我正在保存图像路径的uri,在onActivityResult()中,我使用以下代码获取位图:
Uri uri = Uri.fromFile(imgFile);
File dest = new File(uri.getPath());
FileInputStream fis;
try {
fis = new FileInputStream(dest);
Bitmap sourceBitmap = BitmapFactory.decodeStream(fis);
...
我的问题是我在我的一部旧手机上得到了一个outofMemoryException,但是却没有使用.decodeStream(),但当我在片段中给视图充气时,我正在调用显示位图:
view = inflater.inflate(R.layout.dialogfragment_image, container, true);
我读到decodeStream()效率不高,占用大量内存。使用内容解析器似乎无法使用某些三星设备。
那么我该怎样做才能防止outOfMemory-Exception?
答案 0 :(得分:1)
Try This Code:-
BitmapFactory.Options options = new BitmapFactory.Options();
options.inDither = false;
options.inJustDecodeBounds = false;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inSampleSize = 1;
options.inPurgeable = true;
options.inPreferQualityOverSpeed = true;
options.inTempStorage=new byte[32 * 1024];
Bitmap sourceBitmap = BitmapFactory.decodeStream(fis,options);
and manifest file in this code use:-
<application
android:allowBackup="true"
android:icon="@drawable/app_icon"
android:label="@string/app_name"
android:largeHeap="true" //This line add in application tag
答案 1 :(得分:0)
您可以使用以下方法将图像缩放到较小的尺寸以防止出现内存错误:
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 2;
if (height >= reqHeight || width >= reqWidth) {
inSampleSize *= 2;
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(String file,
int reqWidth, int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(file, options);
}