在将5或6个图库图片加载到我的应用中后,我不断获得Out Of Memory Errors
。
我在每个图片完成加载后调用bitmap.recycle()
,所以想知道为什么我仍然会收到OOM
错误?
这是我处理图库图片的方式:
将图片加载到ImageView
public static void compressAndRotateImage(Context context, String filename) {
try {
File file = new File(context.getExternalFilesDir(null), filename);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(file), null, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 720;
// Find the correct scale value. It should be the power of 2.
int scale = 1;
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 bm = BitmapFactory.decodeStream(new FileInputStream(file), null, o2);
// Get orientation of picture
ExifInterface exif = null;
try { exif = new ExifInterface(context.getExternalFilesDir(null) + "/" + filename); }
catch (IOException e1) { e1.printStackTrace(); }
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1);
Log.i("ORIENTATION", Integer.toString(orientation));
// Rotate image to portrait based on taken orientation
Matrix matrix = new Matrix();
if (orientation == 6) { matrix.postRotate(90); }
else if (orientation == 3) { matrix.postRotate(180); }
else if (orientation == 8) { matrix.postRotate(270); }
bm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
// Save and compress file
FileOutputStream fos = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, 90, fos);
try { fos.flush(); fos.close(); }
catch (IOException e) { e.printStackTrace(); }
bm.recycle();
System.gc();
}
catch (FileNotFoundException e) { e.printStackTrace(); }
}
将图库图片复制到应用外部文件目录
private void copyGalleryImage(Uri uri) {
String realPath = ImageHandler.getRealPathFromUri(this, uri);
File galleryFile = new File(realPath);
imgFilename = ImageHandler.getImageFilename(this);
File file = new File(getExternalFilesDir(null), imgFilename);
GlobalMethods.copyFile(galleryFile, file);
Log.i("IMAGE COPIED TO INTERNAL", imgFilename);
ImageHandler.compressAndRotateImage(this, imgFilename);
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
NewPictureFragment fragment = NewPictureFragment.newInstance(imgFilename);
ft.replace(R.id.fragment_container, fragment);
ft.addToBackStack(null);
ft.commit();
}
答案 0 :(得分:2)
在清单文件中使用android:largeHeap="true"
。也许这可以解决你的问题。