我的应用程序需要上传图片。
为此,我需要从安卓设备的图库获取图片。
我该如何编写代码来完成这个任务?
使用动作为ACTION_GET_CONTENT
,类型为"image/*
"的Intent,将会启动照片选择器Activity。当用户选择一张图片后,您可以使用onActivityResult
回调来获取结果。
类似这样:
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK)
{
Uri chosenImageUri = data.getData();
Bitmap mBitmap = null;
mBitmap = Media.getBitmap(this.getContentResolver(), chosenImageUri);
}
}