Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

java - OutOfMemoryError while decoding and encoding Base64 String into Bitmap

I'm trying to decode and encode a Bitmap image. On some devices it runs perfectly while on others it's not. I'm uploading Base64 String to the server and getting Base64 String from the server. I've found various solutions but still am not able to solve my issue. Here's my code:

Encoding:

button1.setOnClickListener(new OnClickListener() {    
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                getActivity().startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
});



//Image loading from Gallery
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
                && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            picturePath = cursor.getString(columnIndex);
            cursor.close();

            imageView1.setImageBitmap(BitmapFactory.decodeFile(picturePath));

            if (picturePath != null && !TextUtils.isEmpty(picturePath)) {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                Bitmap bitmap = BitmapFactory.decodeFile(picturePath, options);
                base64ImageSend = ImageBase64.encodeTobase64(bitmap);
                Log.i("Base 64 Image", base64ImageSend);
            } else {
                base64ImageSend = "";
            }

        }
}

Decoding:

private String base64StringReceive = "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQE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T8cf2+dPvzp3/C/ /bP/AAgHgHszgf8AMBz7eoDDoBk/jf8AqvHu/vX/AMs/ruz9Q/1qn5/+Af8ABP1536n/AM+F/wD+ AP8A9hWHrusWHg7w/qXiHxfqFh4f0DTv+QhqN/ef2f3IPuO2PxGQOa/InTPjT+39qGdOv/jj2H/N Pvh99v6n/qA9u/sVORw1ex+Dvgb8Rfilr9h4h+NvxC8W/ED+zsDTtP167H2Cw+Zsf2TpWf7BPGcc 4+po/wBV4fzv7pf/ACR0/wBvL+790f8A5WbcM/iL9qT4naf4g/s+/sPhj4Q1D/ijtNv86f8A2jgt /avjbVjg+x8Gc+oJOPG5r+lH9nvRLPw98FPh7pliB5Z0Fb9SOu3Vb+fV23EnqDqQ98HqeS35U+Cv A2naDp/9nafYY7A+vJyOwHC8evrknP6//CvDfDfwVnp/wjWicfSwj9/x/Tmv2XgHCLBxmrJ3S03+ 1JLV7vXV+bV9Gfk/GGK+uyTur33T1f8AEUbqy7u1tNGk9LnpNFFFfpx8WFFFFABRRRQAUUUUAFFF FABRRRQAUUUUAFFFFABRRRQAUUUUAFFUJLlbNC12w2kjDAZHVh0JGOh/XqTk+Wa38YfCGnFl08Xe vXQVQn9mg/Yv4851M/Io6Y+9nJ4UjJAOh8e6kmneHr08Fr0fYV+rbwx9uDjv04BIJPyXqBABHqOP w/z/APrrr21S+8fX+o6hfn7DfacB/Z9hz/xL7As/zHj5ix5Y9csc9a4TVl/s1Tg4PGWx15bGMkjn ufpySQB8JxnhXgk7t7K91p

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When showing Bitmap in ImageView from a file first decode it with the help of BitmapHelper.decodeFile(picturePath, 200, 200, true) this will return compressed Bitmap so that while encoding this Bitmap you can handle high resolution images as well as heavy size images upto 100 MB of file.

After decoding file set it to your ImageView and to get Base64 String form above compressed image using BitmapHelper class; get Bitmap from your ImageView (i.e. already been compressed) and use ImageBase64.encodeTobase64(bitmap) this will again compress the file and make handle OutOfMemory exception while Encoding a Bitmap.

For decoding first write your Base64String to file in your device memory. Then read Bytes in chunks and decode that ByteArray by this you will have your bitmap in your memory. After this scale down this bitmap using decodeFile() method then you will have compressed Bitmap from Base64String

I have searched various blogs and post and from them I have taken best suitable code and combined them into one to make more reliable. Try below code to make encoding and decoding more faster with meory management.

To decode Base64String

Bitmap bitmap = ImageBase64.decodeBase64(base64ImageStr,MainActivity.this);
imageView.setImageBitmap(bitmap);
bitmap = null;
System.gc();

To encode Bitmap Try this:

imageView.setImageBitmap(BitmapHelper.decodeFile(picturePath, 200, 200, true));

Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();              
base64ImageStr = ImageBase64.encodeTobase64(bitmap);

Try This code for ImageBase64

public class ImageBase64 {

    private ImageBase64() {
        super();
    }
    private static Context appContext;

    public static String encodeTobase64(Bitmap image) {

         ByteArrayOutputStream baos=new  ByteArrayOutputStream();
         image.compress(Bitmap.CompressFormat.JPEG,100, baos);
            byte [] b=baos.toByteArray();
            String temp=null;
            try{
            System.gc();
            temp=Base64.encodeToString(b, Base64.DEFAULT);
            }catch(Exception e){
                e.printStackTrace();
            }catch(OutOfMemoryError e){
                baos=new  ByteArrayOutputStream();
                image.compress(Bitmap.CompressFormat.JPEG,50, baos);
                b=baos.toByteArray();
                temp=Base64.encodeToString(b, Base64.DEFAULT);
                Log.e("EWN", "Out of memory error catched");
            }
            return temp;
    }


    public static Bitmap decodeBase64(String input,Context context) {
        byte[] decodedByte = Base64.decode(input, 0);

        appContext = context;
        Boolean isSDPresent = android.os.Environment
                .getExternalStorageState().equals(
                        android.os.Environment.MEDIA_MOUNTED);

        File sdCardDirectory;
        if (isSDPresent) {
            // yes SD-card is present
             sdCardDirectory = new File(
                        Environment
                                .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                        "IMG");

                if (!sdCardDirectory.exists()) {
                    if (!sdCardDirectory.mkdirs()) {
                        Log.d("MySnaps", "failed to create directory");

                    }
                }
        } else {
            // Sorry
            sdCardDirectory = new File(context.getCacheDir(),"");
        }



        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                .format(new Date());

        Random rand = new Random();

        // nextInt is normally exclusive of the top value,
        // so add 1 to make it inclusive
        int randomNum = rand.nextInt((1000 - 0) + 1) + 0;

        String nw = "IMG_" + timeStamp + randomNum+".txt";
        File image = new File(sdCardDirectory, nw);



        // Encode the file as a PNG image.
        FileOutputStream outStream;
        try {


            outStream = new FileOutputStream(image);
            outStream.write(input.getBytes());

            outStream.flush();
            outStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        Log.i("Compress bitmap path", image.getPath());
        Bitmap bitmap;
        try{
        bitmap = BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
        }catch(OutOfMemoryError e){
            e.printStackTrace();
            InputStream is = context.getResources().openRawResource(R.drawable.default_profile_pic);
            bitmap  = BitmapFactory.decodeStream(is);  

        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            bitmap=null;
        }

        return bitmap;//BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
        //return decodeFile(image); 
    }

    private static Bitmap decodeFile(File f){
        try {
            //Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);

            //The new size we want to scale to
            final int REQUIRED_SIZE=70;

            //Find the correct scale value. It should be the power of 2.
            int scale=1;
            while(o.outWidth/scale>=REQUIRED_SIZE && o.outHeight/scale>=REQUIRED_SIZE)
                scale*=2;

            //Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;

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


            Boolean isSDPresent = android.os.Environment
                    .getExternalStorageState().equals(
                            android.os.Environment.MEDIA_MOUNTED);
            File sdCardDirectory;
            if (isSDPresent) {
                // yes SD-card is present
                 sdCardDirectory = new File(
                            Environment
                                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                            "IMG");

                    if (!sdCardDirectory.exists()) {
                        if (!sdCardDirectory.mkdirs()) {
                            Log.d("MySnaps", "failed to create directory");

                        }
                    }
            } else {
                // Sorry
                sdCardDirectory = new File(appContext.getCacheDir(),"");
            }



            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                    .format(new Date());

            Random rand = new Random();

            // nextInt is normally exclusive of the top value,
            // so add 1 to make it inclusive
            int randomNum = rand.nextInt((1000 - 0) + 1) + 0;

            String nw = "IMG_" + timeStamp + randomNum+".png";
            File image = new File(sdCardDirectory, nw);



            FileOutputStream out = null;
            try {
                out = new FileOutputStream(image);
                bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
                // PNG is a lossless format, the compression factor (100) is ignored
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            String pathNew =compressImage(image.getAbsolutePath());
            Uri uri = Uri.parse(pathNew);   
            Bitmap bitmap=null ;
            try {
                 bitmap     = MediaStore.Images.Media.getBitmap(appContext.getContentResolver(),uri);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return bitmap;
        } catch (FileNotFoundException e) {}
        return null;
    }


    public static String compressImage(String imageUri) {

        String filePath = imageUri;//getRealPathFromURI(imageUri);
        Bitmap scaledBitmap = null;

        BitmapFactory.Options options = new BitmapFactory.Options();

//      by setting this field as true, the actual bitmap pixels are not loaded in the memory. Just the bounds are loaded. If
//      you try the use the bitmap here, you will get null.
        options.inJustDecodeBounds = true;
        Bitmap bmp = BitmapFactory.decodeFile(filePath, options);

        int actualHeight = options.outHeight;
        int actualWidth = options.outWidth;

//      max Height and width values of the compressed image is taken as 816x612

        float maxHeight = 816.0f;
        float maxWidth = 612.0f;
        float imgRatio = actualWidth / actualHeight;
        float maxRatio = maxWidth / maxHeight;

//      width and height values are set maintaining the aspect ratio of the image

        if (actualHeight > maxHeight || actualWidth > maxWidth) {
            if (imgRatio < maxRatio) {               imgRatio = maxHeight / actualHeight;                actualWidth = (int) (imgRatio * actualWidth);               actualHeight = (int) maxHeight;             } else if (imgRatio > maxRatio) {
                imgRatio = maxWidth / actualWidth;
                actualHeight = (int) (imgRatio * actualHeight);
                actualWidth = (int) maxWidth;
            } else {
                actualHeight = (int) maxHeight;
                actualWidth = (int) maxWidth;

            }
        }

//      setting inSampleSize value allows to load a scaled down version of the original image

        options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);

//      inJustDecodeBounds set to false to load the actual bitmap
        options.inJustDecodeBounds = false;

//      this options allow android to claim the bitmap memory if it runs low on memory
        options.inPurgeable = true;
        options.inInputShareable = true;
        options.inTempStorage = new byte[16 * 1024];

        try {
//          load the bitmap from its path
            bmp = BitmapFactory.decodeFile(filePath, options);
        } catch (OutOfMemoryError exception) {
            exception.printStackTrace();

        }
        try {
            scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight,Bitmap.Config.ARGB_8888);
        } catch (OutOfMemoryError exception) {
            exception.printStackTrace();
        }

        float ratioX = actualWidth / (float) options.outWidth;
        float ratioY = actualHeight / (float) options.outHeight;
        float middleX = actualWidth / 2.0f;
        float middleY = actualHeight / 2.0f;

        Matrix scaleMatrix = new Matrix();
        scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);

        Canvas canvas = new Canvas(scaledBitmap);
        canvas.setMatrix(scaleMatrix);
        canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Pain

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...