简体   繁体   中英

How to upload image from gallery in android

I want to upload image from my phone gallery into my application .In my application there is button named upload. when i click button,it should move to gallery and in gallery if i select image that selected image should display as thumbnail in application.I want to upload 10 images, from gallery in my application.

On click of the gallery button, start startActivityForResult as follows:

startActivityForResult(new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI), GET_FROM_GALLERY);

Consequently, detect GET_FROM_GALLERY (which is a static int, any request number of your choice eg, public static final int GET_FROM_GALLERY = 3; ) inside onActivityResult.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);


    //Detects request codes
    if(requestCode==GET_FROM_GALLERY && resultCode == Activity.RESULT_OK) {
        Uri selectedImage = data.getData();
        Bitmap bitmap = null;
        try {
                bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
        } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        }
    }
}

To view gallery:

Intent intent = new Intent();
  intent.setType("image/*");
  intent.setAction(Intent.ACTION_GET_CONTENT);
  startActivityForResult(Intent.createChooser(intent, "Select Picture"),REQUEST_CODE);

and to use it in your app:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  try {
   switch (requestCode) {

   case REQUEST_CODE:
    if (resultCode == Activity.RESULT_OK) {
     //data gives you the image uri. Try to convert that to bitmap
     break;
    } else if (resultCode == Activity.RESULT_CANCELED) {
     Log.e(TAG, "Selecting picture cancelled");
    }
    break;
   }
  } catch (Exception e) {
   Log.e(TAG, "Exception in onActivityResult : " + e.getMessage());
  }
 }

This is the way to go:

startActivityForResult(
  new Intent(
    Intent.ACTION_PICK,
    android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI
  ),
  GET_FROM_GALLERY
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM