我有内容://图片的URI,我想将其转换为base64。我不知道该怎么做。我在这个问题上苦苦挣扎了2天,所以请解释为什么以及你的解决方案如何运作。
这是我的代码:
@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());
}
}
}
请不要关注这篇文章。我真的需要帮助
答案 0 :(得分:2)
您可以使用两个步骤来完成。
1- URI到位图转换:
@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字符串转换:
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
byte[] byteArray = outputStream.toByteArray();
String encodedString = Base64.encodeToString(byteArray, Base64.DEFAULT);
结果:
@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);
}
}
}