Image capture for Base64

Asked

Viewed 530 times

3

Man app take an image from the gallery or take a photo, how to grab this image and convert to Base64?

  private void onCaptureImageResult(Intent data) {
    Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    thumbnail.compress(Bitmap.CompressFormat.PNG, 90, bytes);
    System.out.println(data);

    File destination = new File(Environment.getExternalStorageDirectory(),
                                System.currentTimeMillis() + ".jpg");
    FileOutputStream fo;

    try {
        destination.createNewFile();
        fo = new FileOutputStream(destination);
        fo.write(bytes.toByteArray());
        fo.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    ivImage.setImageBitmap(thumbnail);
}

@SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
    Bitmap bm=null;

    if (data != null) {
        try {
            bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    ivImage.setImageBitmap(bm);
}

1 answer

3


Just create a vector of bytes to receive the ByteArrayOutputStream using the method toByteArray converting bytes to a vector of bytes. Soon after import the lib android.util.Base64, create a string to receive the Base64 converting to string through the method encodeToString. Take an example:

byte[] b = bytes.toByteArray();
String encodedfile = Base64.encodeToString(b, Base64.DEFAULT);
  • 1

    It worked perfectly! Thank you !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.