Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - How can I get image from ClipData?

I'm creating an image uploader that has the ability to upload more than 1 images at once.

galerijButton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);

        photoPickerIntent.setType("image/*");
        startActivityForResult(photoPickerIntent, SELECT_PHOTO);   
    }
});

...

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

    switch(requestCode) { 
    case SELECT_PHOTO:
        if(resultCode == RESULT_OK){  
            if(imageReturnedIntent.getData() != null){
                //If uploaded with Android Gallery (max 1 image)
                Uri selectedImage = imageReturnedIntent.getData();
                InputStream imageStream;
                try {
                    imageStream = getContentResolver().openInputStream(selectedImage);
                    Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
                    photos.add(yourSelectedImage);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            } else {
                //If uploaded with the new Android Photos gallery
                ClipData clipData = imageReturnedIntent.getClipData();
                for(int i = 0; i < clipData.getItemCount(); i++){
                    clipData.getItemAt(i);
                    //What now?
                }
            }
        }
    break;
    ....

I would like to add all the selected images to my photos array which is an ArrayList<Bitmap> . Somehow I have to convert the ClipData.Item to Bitmap, but how?

like image 481
Bart Burg Avatar asked Feb 13 '14 10:02

Bart Burg


2 Answers

try this

ClipData.Item item = clip.getItemAt(i);
Uri uri = item.getUri();

now you have the URIs of the images.

I guess you know what to do now. Cheers :)

like image 113
SMR Avatar answered Nov 03 '22 13:11

SMR


Achieved with a Kotlin one liner:

private fun ClipData.convertToList(): List<Uri> = 0.until(itemCount).map { getItemAt(it).uri }
like image 30
Haider Malik Avatar answered Nov 03 '22 13:11

Haider Malik