Search code examples
androidbase64uriandroid-gallery

get base64 URI result from ACTIVITY_GET_CONTENT (Android)


In an android app I'm developing, I want the user to pick an image from their gallery, and for that, i'm using this code:

private void takePictureFromGallery(int pick) {
    startActivityForResult(
            Intent.createChooser(new Intent(Intent.ACTION_GET_CONTENT).setType("image/*"), "Choose an image"), pick);
}

And I'm using onActivityResult to detect when an image has been selected. Since I want the URI of the image, I call

Uri selectedImageUri = data.getData();

But that only returns "/document/image:28" as an output.

What would be the process of instead receiving a Base64-type URI (one that begins with "data:image/gif;base64,{base64 encoded image}") that represents the image?

Thanks In Advance.


Solution

  • Uri selectedImageUri = data.getData();
    

    That statement is useless. That is akin to thinking that /questions/34245601/get-base64-uri-result-from-activity-get-content-android (the path portion of the URL of this Web page) is somehow meaningful in isolation.

    What would be the process of instead receiving a Base64-type URI (one that begins with "data:image/gif;base64,{base64 encoded image}") that represents the image?

    Step #1: Use a ContentResolver to openInputStream() on that Uri.

    Step #2: Read in the bytes and convert them to base64, appending them to the end of a URL that has your desired prefix.

    Step #3: Be prepared for OutOfMemoryErrors, as you may not have enough heap space for your string, depending on the state of your heap and the size of the image that the user chooses.