Java 位图创建内存不足

Java 位图创建内存不足,java,android,bitmap,out-of-memory,Java,Android,Bitmap,Out Of Memory,我正在尝试从照相机的意图在活动结果()上旋转拍摄的图像,但偶尔会出现内存不足错误 如何优化此代码 我试图在这些行之后添加bmp.recycle()和correctmbmp.recycle(),但没有帮助。尝试在解码流之前添加下面的代码,并将选项作为参数传递 BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 5; op

我正在尝试从照相机的意图在活动结果()上旋转拍摄的图像,但偶尔会出现内存不足错误

如何优化此代码


我试图在这些行之后添加
bmp.recycle()
correctmbmp.recycle()
,但没有帮助。

尝试在解码流之前添加下面的代码,并将选项作为参数传递

BitmapFactory.Options options = new BitmapFactory.Options();                
options.inSampleSize = 5;               
options.inPurgeable = true;             
options.inInputShareable = true;


bmp = BitmapFactory.decodeStream(new FileInputStream(f),null, options);

如果您开发了10级以上的应用程序api,您可以在下面添加清单

 android:largeHeap="true" //add this entity.


多亏了这些代码,您还可以调整位图的大小。

不要只从外部链接到代码:直接在帖子中添加相关的代码片段,如果您仍然认为有必要,可以链接到整个代码。您需要将图片稍微缩小一点,尝试在SampleSize中查找
Better,以便根据需要重新采样位图,使其适合屏幕。试着看看另一个类似的线程中发布的我的答案可能会对您有所帮助:创建选项以帮助使用更少的内存,如果您愿意,您可以添加options.inPreferredConfig=Bitmap.Config.rgb565;在真正需要之前,将“largeHeap”加载到清单不是一个好的实践。
 android:largeHeap="true" //add this entity.
  <application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:largeHeap="true"
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >
   public Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
        int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth,
            reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}

public static int calculateInSampleSize(BitmapFactory.Options options,
        int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {
        if (width > height) {
            inSampleSize = Math.round((float) height / (float) reqHeight);
        } else {
            inSampleSize = Math.round((float) width / (float) reqWidth);
        }
    }
    return inSampleSize;
}