How to pick an image from gallery (SD Card) for my app?

前端 未结 10 1878
Happy的楠姐
Happy的楠姐 2020-11-21 23:40

This question was originally asked for Android 1.6.

I am working on photos options in my app.

I have a button and an ImageView in my Activity. When I click

相关标签:
10条回答
  • 2020-11-22 00:20

    Updated answer, nearly 5 years later:

    The code in the original answer no longer works reliably, as images from various sources sometimes return with a different content URI, i.e. content:// rather than file://. A better solution is to simply use context.getContentResolver().openInputStream(intent.getData()), as that will return an InputStream that you can handle as you choose.

    For example, BitmapFactory.decodeStream() works perfectly in this situation, as you can also then use the Options and inSampleSize field to downsample large images and avoid memory problems.

    However, things like Google Drive return URIs to images which have not actually been downloaded yet. Therefore you need to perform the getContentResolver() code on a background thread.


    Original answer:

    The other answers explained how to send the intent, but they didn't explain well how to handle the response. Here's some sample code on how to do that:

    protected void onActivityResult(int requestCode, int resultCode, 
           Intent imageReturnedIntent) {
        super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 
    
        switch(requestCode) { 
        case REQ_CODE_PICK_IMAGE:
            if(resultCode == RESULT_OK){  
                Uri selectedImage = imageReturnedIntent.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
    
                Cursor cursor = getContentResolver().query(
                                   selectedImage, filePathColumn, null, null, null);
                cursor.moveToFirst();
    
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String filePath = cursor.getString(columnIndex);
                cursor.close();
    
    
                Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
            }
        }
    }
    

    After this, you've got the selected image stored in "yourSelectedImage" to do whatever you want with. This code works by getting the location of the image in the ContentResolver database, but that on its own isn't enough. Each image has about 18 columns of information, ranging from its filepath to 'date last modified' to the GPS coordinates of where the photo was taken, though many of the fields aren't actually used.

    To save time as you don't actually need the other fields, cursor search is done with a filter. The filter works by specifying the name of the column you want, MediaStore.Images.Media.DATA, which is the path, and then giving that string[] to the cursor query. The cursor query returns with the path, but you don't know which column it's in until you use the columnIndex code. That simply gets the number of the column based on its name, the same one used in the filtering process. Once you've got that, you're finally able to decode the image into a bitmap with the last line of code I gave.

    0 讨论(0)
  • 2020-11-22 00:21

    call chooseImage method like-

    public void chooseImage(ImageView v)
    {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, SELECT_PHOTO);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
    
        if(imageReturnedIntent != null)
        {
            Uri selectedImage = imageReturnedIntent.getData();
        switch(requestCode) { 
        case SELECT_PHOTO:
            if(resultCode == RESULT_OK)
            {
                Bitmap datifoto = null;
                temp.setImageBitmap(null);
                Uri picUri = null;
                picUri = imageReturnedIntent.getData();//<- get Uri here from data intent
                 if(picUri !=null){
                   try {
                       datifoto = android.provider.MediaStore.Images.Media.getBitmap(this.getContentResolver(),                                 picUri);
                       temp.setImageBitmap(datifoto);
                   } catch (FileNotFoundException e) {
                      throw new RuntimeException(e);
                   } catch (IOException e) {
                      throw new RuntimeException(e);
                   } catch (OutOfMemoryError e) {
                    Toast.makeText(getBaseContext(), "Image is too large. choose other", Toast.LENGTH_LONG).show();
                }
    
            }
            }
            break;
    
    }
        }
        else
        {
            //Toast.makeText(getBaseContext(), "data null", Toast.LENGTH_SHORT).show();
        }
    }
    
    0 讨论(0)
  • 2020-11-22 00:24
    private static final int SELECT_PHOTO = 100;
    

    Start intent

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

    Process result

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
        super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 
    
        switch(requestCode) { 
        case SELECT_PHOTO:
            if(resultCode == RESULT_OK){  
                Uri selectedImage = imageReturnedIntent.getData();
                InputStream imageStream = getContentResolver().openInputStream(selectedImage);
                Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
            }
        }
    }
    

    Alternatively, you can also downsample your image to avoid OutOfMemory errors.

    private Bitmap decodeUri(Uri selectedImage) throws FileNotFoundException {
    
            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o);
    
            // The new size we want to scale to
            final int REQUIRED_SIZE = 140;
    
            // Find the correct scale value. It should be the power of 2.
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp / 2 < REQUIRED_SIZE
                   || height_tmp / 2 < REQUIRED_SIZE) {
                    break;
                }
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }
    
            // Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            return BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o2);
    
        }
    
    0 讨论(0)
  • 2020-11-22 00:24

    Do this to launch the gallery and allow the user to pick an image:

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("image/*");
    startActivityForResult(intent, IMAGE_PICK);
    

    Then in your onActivityResult() use the URI of the image that is returned to set the image on your ImageView.

    0 讨论(0)
提交回复
热议问题