如何更正此错误:java.lang.OutOfMemoryError [英] how to correct this error: java.lang.OutOfMemoryError

查看:59
本文介绍了如何更正此错误:java.lang.OutOfMemoryError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

public void onPictureTaken(byte[] data, Camera camera) {
    Bitmap foto = BitmapFactory.decodeByteArray(data, 0, 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, 0f, null);
    if (newImage.getWidth() > newImage.getHeight()) {
        Matrix matrix = new Matrix();
        matrix.postRotate(90);
        newImage.createBitmap(newImage, 0, 0, wid, hgt, 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堆的限制,因此会发生这种情况,因此您需要缩小图像或降低图像质量.

ost of times this happens due to large bitmap cross the limit of VM heap, so you need to scale down your image or to lower the quality of you image.

要缩放图像,请使用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()降低图像质量.

您还可以按照以下

And you can also follow this conversation to avoid memory error while loading images in Bitmap.

这篇关于如何更正此错误:java.lang.OutOfMemoryError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆