Kin*_*pia 5 android photo gallery
我要求用户通过代码作为监听器访问图库:
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
Run Code Online (Sandbox Code Playgroud)
但是,我对如何将变量设置为所选照片感到困惑.
在选择照片时,我会将代码放在哪里设置变量?
谢谢 :)
Aka*_*ose 14
首先,您必须覆盖onActivityResult
以获取文件所选图像的uri
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == SELECT_PHOTO) {
if (resultCode == RESULT_OK) {
if (intent != null) {
// Get the URI of the selected file
final Uri uri = intent.getData();
useImage(uri);
}
}
super.onActivityResult(requestCode, resultCode, intent);
}
}
Run Code Online (Sandbox Code Playgroud)
然后定义useImage(Uri)
使用图像
void useImage(Uri uri)
{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
//use the bitmap as you like
imageView.setImageBitmap(bitmap);
}
Run Code Online (Sandbox Code Playgroud)
Boj*_*man 11
你可以这样做.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Here we need to check if the activity that was triggers was the Image Gallery.
// If it is the requestCode will match the LOAD_IMAGE_RESULTS value.
// If the resultCode is RESULT_OK and there is some data we know that an image was picked.
if (requestCode == LOAD_IMAGE_RESULTS && resultCode == RESULT_OK && data != null) {
// Let's read picked image data - its URI
Uri pickedImage = data.getData();
// Let's read picked image path using content resolver
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
// Do something with the bitmap
// At the end remember to close the cursor or you will end with the RuntimeException!
cursor.close();
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
22828 次 |
最近记录: |