Skip to content

Instantly share code, notes, and snippets.

@dyazincahya
Last active February 1, 2024 17:57
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dyazincahya/8eb2c63afda9d049944ba2257e3edad7 to your computer and use it in GitHub Desktop.
Save dyazincahya/8eb2c63afda9d049944ba2257e3edad7 to your computer and use it in GitHub Desktop.
ANDROID - TAKE A PHOTO WITH CAMERA IN KOTLIN (https://kang-cahya.com)

TAKE A PHOTO WITH CAMERA IN KOTLIN

SETTING

Step-1

Create provider_paths.xml in res/xml folder and write below code in it.

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path
        name="external_files"
        path="." />
</paths>

Step-2

Declare provider in manifests/AndroidManifest.xml as below. Put this code in tag application.

<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}.provider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/provider_paths" />
</provider>

Step-3

You have to add some permissions like READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE and CAMERA. Add this code in manifests/AndroidManifest.xml. Put this code in tag manifest.

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

Step-4

You can add a feature from camera like autofocus. Add this code in manifests/AndroidManifest.xml. Put this code in tag manifest.

<uses-feature android:name="android.hardware.camera" android:required="true" />  
<uses-feature android:name="android.hardware.camera.autofocus" />

THE CODE

1. Trigger button

This is a listener button for trigger function openCamera()

btn_takephoto.setOnClickListener {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        openCamera()
    } else {
        longToast("Sorry you're version android is not support, Min Android 6.0 (Marsmallow)")
    }
}

2. Open camera

You can set directory folder and filename here.

private fun openCamera() {
    val values = ContentValues()
    values.put(MediaStore.Images.Media.TITLE, "New Picture")
    values.put(MediaStore.Images.Media.DESCRIPTION, "From the Camera")

    //camera intent
    val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)

	// set filename
    val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
    vFilename = "FOTO_" + timeStamp + ".jpg"

	// set direcory folder
    val file = File("/sdcard/niabsen/", vFilename);
    val image_uri = FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".provider", file);

    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri)
    startActivityForResult(cameraIntent, IMAGE_CAPTURE_CODE)
}

3. Request Permission

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
    //called when user presses ALLOW or DENY from Permission Request Popup
    when(requestCode){
        PERMISSION_CODE -> {
            if (grantResults.size > 0 && grantResults[0] ==
                PackageManager.PERMISSION_GRANTED){
                //permission from popup was granted
                openCamera()
            }
            else{
                //permission from popup was denied
                toast("Permission denied")
            }
        }
    }
}

4. Activity Result

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {

        //File object of camera image
        val file = File("/sdcard/niabsen/", vFilename);
        longToast(file.toString())
        
        //Uri of camera image
        val uri = FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".provider", file);
        myImageView.setImageURI(uri)
    }
}

FULL KOTLIN CODE

class ExampleCode : AppCompatActivity() {
    private val PERMISSION_CODE = 1000
    private val IMAGE_CAPTURE_CODE = 1001

    var vFilename: String = ""


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.example_code)

        btn_takephoto.setOnClickListener {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                openCamera()
            } else {
                longToast("Sorry you're version android is not support, Min Android 6.0 (Marsmallow)")
            }
        }
    }

    private fun openCamera() {
        val values = ContentValues()
        values.put(MediaStore.Images.Media.TITLE, "New Picture")
        values.put(MediaStore.Images.Media.DESCRIPTION, "From the Camera")

        //camera intent
        val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)

        // set filename
        val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
        vFilename = "FOTO_" + timeStamp + ".jpg"

        // set direcory folder
        val file = File("/sdcard/niabsen/", vFilename);
        val image_uri = FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".provider", file);

        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri)
        startActivityForResult(cameraIntent, IMAGE_CAPTURE_CODE)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        //called when user presses ALLOW or DENY from Permission Request Popup
        when(requestCode){
            PERMISSION_CODE -> {
                if (grantResults.size > 0 && grantResults[0] ==
                    PackageManager.PERMISSION_GRANTED){
                    //permission from popup was granted
                    openCamera()
                } else{
                    //permission from popup was denied
                    toast("Permission denied")
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

            //File object of camera image
            val file = File("/sdcard/niabsen/", vFilename);
            longToast(file.toString())
            
            //Uri of camera image
            val uri = FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".provider", file);
            myImageView.setImageURI(uri)
        }
    }
}


@moahear
Copy link

moahear commented Jul 12, 2023

hi, thanks a lot and best regards

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment