How to fix this error: java.lang.OutOfMemoryError

This is my code:

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); } } 

That's my fault:

 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) 
+7
android memory out-of-memory
source share
2 answers

Sometimes this is due to the large bitmap crossing the border of the VM heap, so you need to zoom out or downgrade the image quality.

Use 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(); } } 

Or use Bitmap.compress() to reduce image quality.

And you can also follow this conversation to avoid a memory error when loading images into a bitmap.

+9
source share

If you are using an emulator, you may have too little for the VM heap for this emulator instance. Check the advanced option in the emulator and try increasing the value for the VM heap. It so happened that it worked in my phone, but not in the emulator, for the low value of the VM heap. In any case, if you do not have a large number of images, they may be too high resolution.

0
source share

All Articles