How to get images from gallery and display them to

2019-05-25 08:30发布

问题:

I would like to know how to get a pre-saved image from the gallery and then display it onto the screen. Any tutorials/helpful links and info would be appreciated. If there is anything you would like me to explain more, please ask.

回答1:

Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);

This Intent used to pick the images from your SD cards and use onActivityResult() for get image and display the image in ImageView.

public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
 {
  if (resultCode == RESULT_OK)
  {
    Uri photoUri = data.getData();
    if (photoUri != null)
    {
    try {
          String[] filePathColumn = {MediaStore.Images.Media.DATA};
          Cursor cursor = getContentResolver().query(photoUri, filePathColumn, null, null, null); 
     cursor.moveToFirst();
 int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
 String filePath = cursor.getString(columnIndex);
 cursor.close();
 Bitmap bMap = BitmapFactory.decodeFile(filePath);
 image.setImageBitmap(bMap);

 }catch(Exception e)
  {}
  }
}
}
}

now we get chossed image from gallery and then set image to ImageVIew.Here image.setImageBitmap(bMap); set the image to ImageView.