androidimagebitmapbase64encode

Getting half image when convert bitmap to base64


I want to upload image to server which is accept images in base64 encored format. I use this code to encode bitmap, But it encode only half of the image and server receive only half of the image part.

This is my code.

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            photo.compress(Bitmap.CompressFormat.PNG, 10, byteArrayOutputStream);
            byte[] byteArray = byteArrayOutputStream .toByteArray();

            String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
// Send to server(encoded)

and when I try to encode image from gallery it pop up a error and crashes the app, with error.

java.lang.OutOfMemoryError: Failed to allocate a 15521174 byte allocation with 13777320 free bytes and 13MB until OOM

I want to encode the full image, any help?


Solution

  • try this code:

     BitmapFactory.Options options;
     options = new BitmapFactory.Options();
    
        // downsizing image as it throws OutOfMemory Exception for larger
        // images
        options.inSampleSize = 6;
       Bitmap bitmap1 = BitmapFactory.decodeFile(fileUri1.getPath(),
                            options);
                    ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
                    if(bitmap1 != null) {
                        bitmap1.compress(Bitmap.CompressFormat.PNG, 10, baos1);
                        byte[] b1 = baos1.toByteArray();
                        bitmapstring1 = Base64.encodeToString(b1,    
    
                       Base64.DEFAULT);