Image capture for base64

3

My app takes an image from the gallery or takes a photo, how to take that image and convert it 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);
}
    
asked by anonymous 03.07.2017 / 15:22

1 answer

3

Just create a bytes vector to get ByteArrayOutputStream using the toByteArray method converting bytes to a bytes vector. Immediately after import the lib android.util.Base64 , create a string to get the Base64 converting to string using the encodeToString method. Here's an example:

byte[] b = bytes.toByteArray();
String encodedfile = Base64.encodeToString(b, Base64.DEFAULT);
    
03.07.2017 / 16:41