I have content:// URI of an image and I want to convert it to base64. I don't know how to do this.
Here is my code:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==123 && resultCode==RESULT_OK) {
Uri selectedfile = data.getData(); //The uri with the location of the file
if (selectedfile != null) {
Log.e("image", selectedfile.toString());
}
}
}
You can do it by using 2 steps.
1- URI to Bitmap conversion:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==123 && resultCode==RESULT_OK) {
Uri selectedfile = data.getData(); //The uri with the location of the file
if (selectedfile != null) {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedfile);
}
}
}
2- Bitmap to Base64 String conversion:
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
byte[] byteArray = outputStream.toByteArray();
String encodedString = Base64.encodeToString(byteArray, Base64.DEFAULT);
As a result:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==123 && resultCode==RESULT_OK) {
Uri selectedfile = data.getData(); //The uri with the location of the file
if (selectedfile != null) {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedfile);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
byte[] byteArray = outputStream.toByteArray();
//Use your Base64 String as you wish
String encodedString = Base64.encodeToString(byteArray, Base64.DEFAULT);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.