Camera URI and Gallery URI

Every now and then I get confused on how to use the data you get back from the camera app or from the gallery. Now I’m saying to myself that I will write this down once and for all to just read it back when I’m confused again!

Photo by Glenn Carstens-Peters on Unsplash

Image from camera

Whenever you get the result back from the Intent that started the camera you will see a parameter called intent.

override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {

Within this intent is a URI called data. When we print this out you will get.

/storage/emulated/0/Android/media/<application_id>/<file_name>.jpg

/storage/emulated/0/ is actually /data/media/0/ exposed through an emulated virtual filesystem. So this URI is pointing to the real location within your phone. You can use this URI in any image loading library.

Image from gallery

Whenever you get the result back from the Intent chooser you will also see a parameter called intent.

override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {

Within this intent is a URI called data. When we print this out you will get.

/content:/media/external/images/media/<number>

If we look up the following in the documentation it states that

A content URI is a URI that identifies data in a provider. Content URIs include the symbolic name of the entire provider (its authority) and a name that points to a table (a path). When you call a client method to access a table in a provider, the content URI for the table is one of the arguments.

So this URI isn’t pointing to the real location of the file. If we read a little bit more we see that

When you want to access data in a content provider, you use the ContentResolver object in your application's Context to communicate with the provider as a client.

So using the contentResolver will give us the data that we want.

val inputStream = context.contentResolver.openInputStream(uri)

Now you can do whatever you want with this input stream. You can make a new file and write the bytes into that file and use the absolute path from that file as the URI you can use in image loading library!

This is also my first post here on Medium. Let me know what you think in the comments :)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store