Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select image from gallery using Kotlin

Tags:

android

kotlin

Recently i have started learning Kotlin. After having some basic functionality i am stuck with image picker.

Does there any specific way to select an image from gallery and camera using Kotlin? Or should i implement in our normal Java code and then call it from Kotlin file?

Java code :

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

Any other difference to perform this operation using Kotlin?

like image 559
Ravi Avatar asked May 24 '17 04:05

Ravi


3 Answers

Here a sample function code for selecting image and capture image:

 fun selectImageInAlbum() {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.type = "image/*"
        if (intent.resolveActivity(packageManager) != null) {
            startActivityForResult(intent, REQUEST_SELECT_IMAGE_IN_ALBUM)
        }
    }
 fun takePhoto() {
        val intent1 = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        if (intent1.resolveActivity(packageManager) != null) {
            startActivityForResult(intent1, REQUEST_TAKE_PHOTO)
        }
    }
 companion object {
        private val REQUEST_TAKE_PHOTO = 0
        private val REQUEST_SELECT_IMAGE_IN_ALBUM = 1
    }

Also don't forget to add this to your manifest file:

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

I hope i can help

like image 107
Melchizedek Avatar answered Nov 25 '22 04:11

Melchizedek


val intent = Intent()
intent.type = "image/*"
intent.action = Intent.ACTION_GET_CONTENT
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE)

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
    super.onActivityResult(requestCode, resultCode, data)
}
like image 44
shinilms Avatar answered Nov 25 '22 06:11

shinilms


Now that startActivityForResult() is Deprecated, this is the new way. First, Do this inside onCreate

Kotlin:

    val selectImageIntent = registerForActivityResult(GetContent())
    { uri ->
        imageView.setImageURI(uri)
    }

Java :

ActivityResultLauncher<String> selectImageIntent = registerForActivityResult(
        new ActivityResultContracts.GetContent(),
        new ActivityResultCallback<Uri>() {
            @Override
            public void onActivityResult(Uri uri) {
                imageView.setImageURI(uri);
            }
        });

And call selectImageIntent.launch("image/*") to launch gallery.

like image 20
Fine Boy Avatar answered Nov 25 '22 04:11

Fine Boy