Get/Pick an Image from Android'S Built-In Gallery App Programmatically

Get/pick an image from Android's built-in Gallery app programmatically

This is a complete solution. I've just updated this example code with the information provided in the answer below by @mad. Also check the solution below from @Khobaib explaining how to deal with picasa images.

Update

I've just reviewed my original answer and created a simple Android Studio project you can checkout from github and import directly on your system.

https://github.com/hanscappelle/SO-2169649

(note that the multiple file selection still needs work)

Single Picture Selection

With support for images from file explorers thanks to user mad.

public class BrowsePictureActivity extends Activity {

// this is the action code we use in our intent,
// this way we know we're looking at the response from our own action
private static final int SELECT_PICTURE = 1;

private String selectedImagePath;

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

findViewById(R.id.Button01)
.setOnClickListener(new OnClickListener() {

public void onClick(View arg0) {

// in onCreate or any event where your want the user to
// select a file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), SELECT_PICTURE);
}
});
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
}
}
}

/**
* helper to retrieve the path of an image URI
*/
public String getPath(Uri uri) {
// just some safety built in
if( uri == null ) {
// TODO perform some logging or show user feedback
return null;
}
// try to retrieve the image from the media store first
// this will only work for images selected from gallery
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if( cursor != null ){
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(column_index);
cursor.close();
return path;
}
// this is our fallback here
return uri.getPath();
}

}

Selecting Multiple Pictures

Since someone requested that information in a comment and it's better to have information gathered.

Set an extra parameter EXTRA_ALLOW_MULTIPLE on the intent:

intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);

And in the Result handling check for that parameter:

if (Intent.ACTION_SEND_MULTIPLE.equals(data.getAction()))
&& Intent.hasExtra(Intent.EXTRA_STREAM)) {
// retrieve a collection of selected images
ArrayList<Parcelable> list = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
// iterate over these images
if( list != null ) {
for (Parcelable parcel : list) {
Uri uri = (Uri) parcel;
// TODO handle the images one by one here
}
}
}

Note that this is only supported by API level 18+.

android pick images from gallery

Absolutely. Try this:

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

Don't forget also to create the constant PICK_IMAGE, so you can recognize when the user comes back from the image gallery Activity:

public static final int PICK_IMAGE = 1;

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == PICK_IMAGE) {
//TODO: action
}
}

That's how I call the image gallery. Put it in and see if it works for you.

EDIT:

This brings up the Documents app. To allow the user to also use any gallery apps they might have installed:

    Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
getIntent.setType("image/*");

Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");

Intent chooserIntent = Intent.createChooser(getIntent, "Select Image");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent});

startActivityForResult(chooserIntent, PICK_IMAGE);

[Android - Kitkat ]Get/pick an image from Android's built-in Gallery app programmatically

This works for Kitkat

public class BrowsePictureActivity extends Activity{

private static final int SELECT_PICTURE = 1;

private String selectedImagePath;
private ImageView imageView;

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.browsepicture);
imageView = (ImageView)findViewById(R.id.imageView1);

((Button) findViewById(R.id.button1))
.setOnClickListener(new OnClickListener() {

public void onClick(View arg0) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), SELECT_PICTURE);
}
});
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
if (Build.VERSION.SDK_INT < 19) {
selectedImagePath = getPath(selectedImageUri);
Bitmap bitmap = BitmapFactory.decodeFile(selectedImagePath);
imageView.setImageBitmap(bitmap);

}
else {
ParcelFileDescriptor parcelFileDescriptor;
try {
parcelFileDescriptor = getContentResolver().openFileDescriptor(selectedImageUri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
imageView.setImageBitmap(image);

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}

/**
* helper to retrieve the path of an image URI
*/
public String getPath(Uri uri) {
if( uri == null ) {
return null;
}
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if( cursor != null ){
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
return uri.getPath();
}

}

You need to add permission

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

How to get an image from gallery after application gets killed?

Solved problem by moving gallery intent to an activity class. Then onActivityResult() method is being triggered.

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

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.

USE an image from Android's built-in Gallery app programmatically

Your getPath() implementation will work on few Android devices, getting fewer by the day. A Uri is not a file.

Use a ContentResolver and openInputStream() to get an InputStream for the Uri you are given in onActivityResult(). Then, use decodeStream() on BitmapFactory to get a Bitmap. Do all of this on a background thread.

Or, use a third-party image loading library (e.g., Picasso, Universal Image Loader) that can do this work for you.

Open an image using URI in Android's default gallery image viewer

Ask myself, answer myself also:

startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("content://media/external/images/media/16"))); /** replace with your own uri */

It will also ask what program to use to view the file.

pick image from gallery and display in imagae view

Finnay this Code is working and we can give fixed size of imageview that display in particular area
layout.xml

 <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Image Upload"
android:id="@+id/buttonImage"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<ImageView

android:layout_width="100dp"
android:layout_height="100dp"
android:id="@+id/imageView"
android:layout_x="13dp"
android:layout_y="112dp" />
Main Activity



Button imageUpload;
ImageView imageView;
static final int PICTURE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView= (ImageView) findViewById(R.id.imageView);
imageUpload= (Button) findViewById(R.id.buttonImage);
imageUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,PICTURE);

}
});
}

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

if (requestCode==PICTURE && resultCode==RESULT_OK && null !=data)
{

Uri uri = data.getData();
String[] prjection ={MediaStore.Images.Media.DATA};
Cursor cursor=getContentResolver().query(uri,prjection,null,null,null);
cursor.moveToFirst();

int columnIndex=cursor.getColumnIndex(prjection[0]);
String path=cursor.getString(columnIndex);
cursor.close();

Bitmap selectFile = BitmapFactory.decodeFile(path);


Drawable d = new BitmapDrawable(selectFile);
imageView.setBackground(d);


// imageView.setImageBitmap(BitmapFactory.decodeFile(path));
}


}

Finally this code is working



Related Topics



Leave a reply



Submit