How to upload image from gallery in android

后端 未结 3 1046
庸人自扰
庸人自扰 2020-12-05 19:34

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 galler

相关标签:
3条回答
  • 2020-12-05 20:03

    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());
      }
     }
    
    0 讨论(0)
  • 2020-12-05 20:06

    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 e.g., 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();
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-05 20:07

    This is the way to go:

    startActivityForResult(
      new Intent(
        Intent.ACTION_PICK,
        android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI
      ),
      GET_FROM_GALLERY
    );
    
    0 讨论(0)
提交回复
热议问题