Android: 如何 select 单击按钮后来自文件管理器的图像?

Android: How to select an Image from a file manager after clicking on a Button?

请问有什么方法可以

  1. 单击按钮时通过 Intent 打开文件管理器
  2. Select 并在 ImageView 中显示该图像
  3. 使用该图像,以便将其转换为 Base64

谢谢

从图库中选择图片

public void pickImage() {
      Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
      intent.setType("image/*");
      startActivityForResult(intent, PICK_PHOTO_FOR_AVATAR);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_PHOTO_FOR_AVATAR && resultCode == Activity.RESULT_OK) {
            if (data == null) {
                //Display an error
                return;
            }
            InputStream inputStream = context.getContentResolver().openInputStream(data.getData());
            //Now you can do whatever you want with your inpustream, save it as file, upload to a server, decode a bitmap...
        }
    }

将图像编码和解码为 Base64

public static String encodeTobase64(Bitmap image)
{
    Bitmap immagex=image;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] b = baos.toByteArray();
    String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);

    Log.e("LOOK", imageEncoded);
    return imageEncoded;
}
public static Bitmap decodeBase64(String input) 
{
    byte[] decodedByte = Base64.decode(input, 0);
    return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length); 
}