Search code examples
javaandroidbase64encode

Turning a Bitmap object into a base64 string having issues


I have a simple application where a image is grabbed from the camera, then passed to my onActivityResult() method. I however can't encode the bitmap object into a base64 string. Eclipes tellsi me that the line byte[] encodedImage = Base64.encode(b, Base64.DEFAULT); should be a byte[] instead of a String, so this is where i think the issue is (hence the line below it trying to force it as a string object). My code is below, this method gets triggered and the Log appears, but the data is NOT base64.

Can anyone help me please.

protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    switch(requestCode){
        case TAKE_PHOTO_CODE:
            if( resultCode == RESULT_OK ){
                Bitmap thumbnail = (Bitmap) intent.getExtras().get("data");
                ByteArrayOutputStream baos = new ByteArrayOutputStream();  
                thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object   
                byte[] b = baos.toByteArray(); 
                byte[] encodedImage = Base64.encode(b, Base64.DEFAULT);
                String encodedImageStr = encodedImage.toString();

                Log.e("LOOK", encodedImageStr);


            }
            // RESULT_CANCELED
        break;          
    }               
}

Solution

  • the toString of array object don't do anything with the contents of the array

    you should use

    String encodedImageStr = new String(encodedImage);
    

    or you can go directly to String with

    String encodedImageStr = Base64.encodeToString(b,Base64.DEFAULT);