Home > Mobile >  How do i add image picker on Android App?
How do i add image picker on Android App?

Time:07-03

im triying to use an image picker so I can open the gallery and choose a pic for the user profile. Apparently the Gradle sync button

Then to need to add import in the java/kotlin source code:

import com.github.dhaval2404.imagepicker.ImagePicker

just like in the sample of that library

CodePudding user response:

Just in case you didn't know, you can already open a file picker that only displays photos - the Photo Picker thing is a new feature in Android 13 (which isn't even released yet), so this is still the standard way to do it!

const val REQUEST_IMAGE_OPEN = 1

fun selectImage() {
    val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
        type = "image/*"
        addCategory(Intent.CATEGORY_OPENABLE)
    }
    // opens the standard document browser, filtered to images
    startActivityForResult(intent, REQUEST_IMAGE_OPEN)
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
    if (requestCode == REQUEST_IMAGE_OPEN && resultCode == Activity.RESULT_OK) {
        val fullPhotoUri: Uri = data.data
        // Do work with full size photo saved at fullPhotoUri
    }
}

There's actually two versions at the link - one uses GET_CONTENT which copies the image, the other uses OPEN_DOCUMENT which gives you a URI pointing to the existing file on disk. Read the descriptions to see which works best for whatever you're doing.

So yeah, if you want something that looks like a plain photo gallery, you'll either need the new picker or a library that does similar. If you just want to let the user load an image though, the standard document browser should be familiar

  • Related