android – 如何更正此错误:java.lang.OutOfMemoryError

前端之家收集整理的这篇文章主要介绍了android – 如何更正此错误:java.lang.OutOfMemoryError前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是我的代码
public void onPictureTaken(byte[] data,Camera camera) {
    Bitmap foto = BitmapFactory.decodeByteArray(data,data.length);
    wid = foto.getWidth();
    hgt = foto.getHeight();

    Bitmap newImage = Bitmap.createBitmap(wid,hgt,Bitmap.Config.ARGB_4444);
    Canvas canvas = new Canvas(newImage);
    canvas.drawBitmap(foto,0f,null);
    if (newImage.getWidth() > newImage.getHeight()) {
        Matrix matrix = new Matrix();
        matrix.postRotate(90);
        newImage.createBitmap(newImage,wid,matrix,true);

    }
}

这是我的错误

FATAL EXCEPTION: main
java.lang.OutOfMemoryError
at android.graphics.Bitmap.nativeCreate(Native Method)
at android.graphics.Bitmap.createBitmap(Bitmap.java:689)
at android.graphics.Bitmap.createBitmap(Bitmap.java:666)
at android.graphics.Bitmap.createBitmap(Bitmap.java:633)
at com.supratecnologia.activity.Camera_Activity.onPictureTaken(Camera_Activity.java:189)
at android.hardware.Camera$EventHandler.handleMessage(Camera.java:768)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)

解决方法

由于大位图超过了VM堆的限制,因此需要缩小图像或降低图像质量.

要缩放图像,请使用BitmapFactory.Options.

Bitmap bm = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 5;
AssetFileDescriptor fileDescriptor =null;
try {
    fileDescriptor = this.getContentResolver().openAssetFileDescriptor(selectedImage,”r”);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
finally{
    try {
        bm = BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(),null,options);
        fileDescriptor.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

或者使用Bitmap.compress()来降低图像质量.

并且您还可以按照此conversation以避免在位图中加载图像时出现内存错误.

猜你在找的Android相关文章