Search code examples
androidbitmapout-of-memoryarraysbmp

Android: conversion from bitmap to Byte[] OutOfMemory error


I try to convert an image saved on the phone's storage (.jpg) to a bitmap and after to convert this bitmap to a byte[] to upload this image on a DB.

public void insertData() {
        File file = new File(photoUrl);
        Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        bytes = stream.toByteArray();
        DBConnUpdate conn = new DBConnUpdate();
        conn.execute(   "insert into test (img, name) "+
                        "values ( '"+ bytes +"', '"+ productName +"')");

    }

but it doesn't works beacause of an OutOfMemory error here:

bytes = stream.toByteArray();

Why?


Solution

  • Try This Code:-
    
    
     BitmapFactory.Options options = new BitmapFactory.Options();
                     options.inDither = false;
                     options.inJustDecodeBounds = false;
                     options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                     options.inSampleSize = 1;
                     options.inPurgeable = true;
                     options.inPreferQualityOverSpeed = true;
                     options.inTempStorage=new byte[32 * 1024];
    
        File file = new File(photoUrl);
                Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 80, stream);
                bytes = stream.toByteArray();