Android:如何在单击按钮后从文件管理器中选择图像?

时间:2016-01-27 03:21:02

标签: android android-intent android-studio onclicklistener

我能知道

的方法吗?
  1. 单击按钮时通过Intent打开文件管理器
  2. 在ImageView中选择并显示该图像
  3. 使用该图像以便可以将其转换为Base64
  4. 谢谢

1 个答案:

答案 0 :(得分:3)

从图库中选择图片

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); 
}