• Skip to main content
  • Skip to secondary menu
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • About
  • Projects
    • GStaticMap WP Plugin
  • Contact
  • Privacy Policy

Lorenz Blog

All About Web & Mobile Application Development

  • Featured Articles
  • Gadgets
    • Android
    • Blackberry
  • Programming
    • Android
    • PHP
    • Java Script
    • MySQL
    • Postgresql
    • Flex
    • Web
  • Software
    • Mac OS
    • Windows
    • Linux
  • Web
You are Here » Home >> Information Technology >> Programming >> Android >> How to Create Android Image Picker

How to Create Android Image Picker

September 9, 2011 by Lorensius Londa 27 Comments

In my previous tutorial on how to select  and crop image on Android, i’ve explained how to create image picker/chooser to select an image from sdcard or camera then crop the selected image. The tutorial is quite advanced and on many cases in our application, we only need to select the image without cropping it. So i made a simplified example to show how to create an image chooser.

public class MainActivity extends Activity {
	private Uri mImageCaptureUri;
	private ImageView mImageView;

	private static final int PICK_FROM_CAMERA = 1;
	private static final int PICK_FROM_FILE = 2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        final String [] items			= new String [] {"From Camera", "From SD Card"};
		ArrayAdapter<String> adapter	= new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
		AlertDialog.Builder builder		= new AlertDialog.Builder(this);

		builder.setTitle("Select Image");
		builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
			public void onClick( DialogInterface dialog, int item ) {
				if (item == 0) {
					Intent intent 	 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					File file		 = new File(Environment.getExternalStorageDirectory(),
							   			"tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
					mImageCaptureUri = Uri.fromFile(file);

					try {
						intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
						intent.putExtra("return-data", true);

						startActivityForResult(intent, PICK_FROM_CAMERA);
					} catch (Exception e) {
						e.printStackTrace();
					}

					dialog.cancel();
				} else {
					Intent intent = new Intent();

	                intent.setType("image/*");
	                intent.setAction(Intent.ACTION_GET_CONTENT);

	                startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
				}
			}
		} );

		final AlertDialog dialog = builder.create();

		mImageView = (ImageView) findViewById(R.id.iv_pic);

		((Button) findViewById(R.id.btn_choose)).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.show();
			}
		});
    }

    @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	    if (resultCode != RESULT_OK) return;

		Bitmap bitmap 	= null;
		String path		= "";

		if (requestCode == PICK_FROM_FILE) {
			mImageCaptureUri = data.getData();
			path = getRealPathFromURI(mImageCaptureUri); //from Gallery

			if (path == null)
				path = mImageCaptureUri.getPath(); //from File Manager

			if (path != null)
				bitmap 	= BitmapFactory.decodeFile(path);
		} else {
			path	= mImageCaptureUri.getPath();
			bitmap  = BitmapFactory.decodeFile(path);
		}

		mImageView.setImageBitmap(bitmap);
	}

	public String getRealPathFromURI(Uri contentUri) {
        String [] proj 		= {MediaStore.Images.Media.DATA};
        Cursor cursor 		= managedQuery( contentUri, proj, null, null,null);

        if (cursor == null) return null;

        int column_index 	= cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

        cursor.moveToFirst();

        return cursor.getString(column_index);
	}
}

The code from my sample project above shows how to create a dialog that shows two options to select the image source. The first is from Camera, where the picture is taken directly from camera, and the second is from saved images on sdcard.

line 14: Define two image source options, From Camera and From SD Card.

line 16-48: Setup the image picker dialog.

line 22: If user choose to take picture from Camera, create an intent to open Camera app with MediaStore.ACTION_IMAGE_CAPTURE action.

line 23: Create temporary file to hold the image from Camera.

line 24: Get the uri of temporary file

line 39: If user choose to select image from sdcard, start the intent to open image chooser dialog. The image chooser dialog will display list File Manager (if exist) apps and default Gallery app.

line 55: show the image picker dialog.

android image picker android image picker

line 61: Override the onActivityResult method to handle the selected image.

line 67: If user selects image from sdcard, get the uri of selected image (line 68)

line 69: Assume user selects the image from sdcard using Gallery app. The uri from Gallery app does not give the real path to selected image, so it has to be resolved on content provider. Method getRealPathFromURI used to resolve the real path from the uri.

line 71: If the path is null, assume user selects the image using File Manager app. File Manager app returns different information than Gallery app. To get the real path to selected image, use getImagePath method from the uri (line 72).

line 75: Get the bitmap.

line 77: If user choose to take picture from camera, get the real path of temporary file that previously defined on line 24-25.

line 78: Get the bitmap.

line 81: Display the bitmap on image view.

android image picker

[ad]

Download source code of this tutorial on my github page

Facebooktwitterredditpinterestlinkedinmailby feather

Related posts:

  1. How to Select and Crop Image on Android
  2. Android Tips: How to Place Image or Logo at The Center of Actionbar
  3. How to Send Image to Twitpic from Android
  4. How to Create QuickAction Dialog in Android

Filed Under: Android, Information Technology, Programming Tagged With: Android, camera, file manager, gallery, image chooser, image picker

About Lorensius Londa

Passionate web and mobile application developer. Co-founder of TRUSTUDIO, loves programming, Android, aviation, travelling, photography, coffee and gym mania.

Reader Interactions

Comments

  1. ravi says

    January 3, 2012 at 12:50 pm

    sir
    thanks this is a wonderful coding you did but i am facing 1 problem that-

    on clicking of camera it is coming for few second after that it is being close with force close,please tell me the solution??

    Reply
  2. Sajay says

    March 12, 2012 at 2:17 pm

    Thank you very much , seriously thank you very much

    Reply
  3. sachin verma says

    April 6, 2012 at 3:49 pm

    thank u so much,so your coding is better to learn pick image for gallery

    Reply
  4. krishna kanth says

    April 18, 2012 at 11:13 am

    hank u so much,so your coding is better and more dynamic. But i have one issue,while using devices with api level above 4, always it is the returning the pic in LANDSCAPE mode. How to solve this problem ??

    Reply
  5. Yugie says

    May 28, 2012 at 8:20 am

    Hallo mas londa, mas saya mau tanya kalau selanjutnya file itu mau dikirim ke server gmna ya? kirim via HTTP Post nya seperti apa ya? Request tutorialnya mas, Thanks Mas.. 🙂

    Reply
  6. Nugraha says

    June 5, 2012 at 3:44 pm

    Hi, how if I want to get the image file path?

    Thanks!

    Reply
  7. Ishan Shah says

    June 25, 2012 at 1:57 pm

    Great code. Great help ! Cheers. Keep publishing & helping ! 🙂

    Reply
  8. Manish says

    June 26, 2012 at 2:52 pm

    Hi!
    Just use below code with your path-
    File f = new File(mImageCaptureUri.getPath());

    Reply
  9. yoga says

    August 1, 2012 at 11:04 am

    Thank’s, Dude..,
    It’s realy help me..,

    Reply
  10. Kyura says

    August 16, 2012 at 5:12 pm

    Thanks for your example. It works almost flawlessly. I have one problem though; When taking a picture via camera intent, it works perfectly in landscape mode, but in portrait mode it somehow loses its data and crashes for null data. Im using galaxy tab 10.1

    Reply
  11. MrBubble says

    September 1, 2012 at 4:15 am

    This was awesome. I had a much more convoluted piece of code that did something similar

    thanks!

    Reply
  12. Conny says

    September 24, 2012 at 3:59 pm

    Hi!
    Great job, thanks very much!
    How can I choose images on eclipse to simulate “Select Image From SD Card”?

    Reply
  13. Pegasus says

    September 24, 2012 at 7:59 pm

    Good stuff!
    Can’t get rid of the distance between the image and the button, any suggestions?

    Reply
  14. nickk says

    October 29, 2012 at 8:03 pm

    great tutorial…I have just one problem please help me…How can I store the image path chosen from SD card to sqlite database….plz help

    Reply
  15. ricky says

    November 2, 2012 at 3:44 pm

    this can filtering by name file or n view name file on picker…on show (Intent.ACTION_GET_CONTENT)

    Reply
  16. app says

    January 6, 2013 at 11:38 am

    Good work, thanks for sharing!

    Reply
  17. Bob says

    February 12, 2013 at 1:34 am

    am new at this, can you share the layout xml please ?

    Reply
  18. romany4 says

    February 13, 2013 at 9:15 am

    Its possible? I want get all content provider and “Get picture from camera” from one menu?

    Reply
  19. devang says

    February 15, 2013 at 2:00 am

    thank you very very much, but can u help me in storing this image in sqlite3? please upload a tutorial for creating the database for storing the captured image.thankz in advance

    Reply
  20. monkry says

    November 19, 2013 at 6:30 pm

    Thank you so much! Worked for me (I only use the part for choosing from file manager though)
    btw, in line 86, there’s:
    Cursor cursor = managedQuery( contentUri, proj, null, null,null);
    but since it’s deprecated, I use:
    Cursor cursor = getContentResolver().query( contentUri, proj, null, null,null);
    it worked, though I don’t know if there’s any side effect…

    Reply
  21. Rahman says

    March 7, 2014 at 4:54 am

    Hi. Thanks for your tutorial. However I got an error on onActivityResult method. It says syntax errors on token, or misplaced contract in the method parameter resultCode. Do you have any idea about this?

    Thank you

    Reply
    • Lorensius Londa says

      March 14, 2014 at 11:43 am

      Hi Rahman,

      What android version did u use?

      Reply
      • Rahman says

        March 23, 2014 at 12:29 am

        Hi,

        Thanks for reply. I am using version 4.4. But now, the problem is solved as I reposition the method in class. No errors at all.

        Hoewever, when I take picture from camera or sd card, my imageview object does not display it. Can you give me your advice? Thanks a lot.

        Reply
        • Dhruv Garg says

          August 27, 2017 at 10:51 pm

          Same is the case with me. Please help!

          Reply
  22. ajit says

    January 12, 2015 at 6:08 pm

    what is this “R.id.iv_pic”, it cannot be resolved in eclipse. Whats the use of it ?
    Same for “R.id.btn_choose” ….

    please do reply

    Reply
  23. Tanka says

    April 1, 2015 at 11:18 am

    For picking image below does not work in mine.

    Intent intent = new Intent();

    intent.setType(“image/*”);
    intent.setAction(Intent.ACTION_GET_CONTENT);

    startActivityForResult(Intent.createChooser(intent, “Complete action using”), PICK_FROM_FILE);

    Instead I replace with :
    Intent intent = new Intent(
    Intent.ACTION_PICK,
    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

    intent.setType(“image/*”);
    startActivityForResult(Intent.createChooser(intent,
    “Complete action using”), SELECT_FILE);

    This worked for me

    Reply
  24. parth says

    June 27, 2017 at 1:20 pm

    Hi the app isnt working on bluestacks can someone help ??

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

About Me

A husband, father of two, passionate software developer, diy lover and home baker who loves to learn new things. Read More…

  • Facebook
  • GitHub
  • Google+
  • Instagram
  • Twitter
  • YouTube

Featured Articles

How to Setup MQTT Server Using Mosquitto and Libwebsocket on Freebsd

Blue Bamboo P25 Printer Android Demo Application With Source Code

Simple JSON RPC Client for Android

How to Send Message to Google Cloud Messaging (GCM) Server Using JSON and PHP

Footer

Recent Comments

  • Aditya Dabas on About
  • Ayten Göksenin Barutçu on How to Make Android Map Scrollable Inside a ScrollView Layout
  • mang jojot on About
  • Hussain on How to Programmatically Scan or Discover Android Bluetooth Devices

Recent Posts

  • How to Fix Blank Screen on WordPress Add/Edit Post Page
  • How to Programmatically Restart the ESP32 Board
  • How to Get Hardware Info of ESP32
  • How to Setup MQTT Server Using Mosquitto and Libwebsocket on Freebsd

Latest Tweets

Could not authenticate you.

Copyright © 2023 · Magazine Pro on Genesis Framework · WordPress · Log in