TheJadav

Get Image from gallery or Camera in android

Get Image from gallery or Camera in android

Select Image from device

IntentChooser to get image from gallery

We need to create chooser intent to select image from device.

    private fun openPickerNow() {
        val getIntent = Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        getIntent.type = "image/*"

        startActivityForResult(Intent.createChooser(getIntent, "Select Image"), PICK_IMAGE)
    }

Get image from camera

  
  var photoFile: File? = null //Global variable
  
  override fun openCamera() {

        Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
            // Ensure that there's a camera activity to handle the intent
            takePictureIntent.resolveActivity(packageManager)?.also {
                // Create the File where the photo should go
                photoFile = try { AppUtils.createImageFile(baseContext)
                } catch (ex: IOException) {
                    // Error occurred while creating the File
                    null
                }
                // Continue only if the File was successfully created
                photoFile?.also {
                    val photoURI: Uri = FileProvider.getUriForFile(this, "$packageName.fileprovider", it)
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
                    startActivityForResult(takePictureIntent, CAPTURE_IMAGE)
                }
            }
        }
    }
  
  

utils methods to create temp image file, get real path from uri

  
  @Throws(IOException::class)
    fun createImageFile(context: Context): File {
        // Create an image file name
        val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
        val storageDir: File? = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        return File.createTempFile(
            "JPEG_${timeStamp}_", /* prefix */
            ".jpg", /* suffix */
            storageDir /* directory */
        ).apply {
            // Save a file: path for use with ACTION_VIEW intents
            return File(absolutePath)
        }
    }

    fun getRealPathFromUri(contentUri: Uri, context: Context): String? {
        var cursor: Cursor? = null
        return try {
            val proj = arrayOf(MediaStore.Images.Media.DATA)
            cursor = context.contentResolver.query(contentUri, proj, null, null, null)
            assert(cursor != null)
            val column_index: Int = cursor!!.getColumnIndexOrThrow(proj[0])
            cursor.moveToFirst()
            cursor.getString(column_index)
        } finally {
            if (cursor != null) {
                cursor.close()
            }
        }
    }
  
  

handle result when image selected from camera or gallery

  
  override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when(requestCode){
            PICK_IMAGE -> {
                if (data == null || data.data == null) {
                    Snackbar.make(
                        cdlSnack,
                        getString(R.string.image_not_selected),
                        Snackbar.LENGTH_SHORT
                    ).show()
                    return
                }

                val path = AppUtils.getRealPathFromUri(data.data!!, baseContext) ?: return
                val file = File(path)
                //We can upload file now
            }

            CAPTURE_IMAGE -> {
                if (photoFile != null){
                    //Here we can upload file
                }
            }
        }
    }
  
  
  

Share this content:

Share:

More Posts

Introduction to Kotlin: A Versatile and Modern Programming Language

Kotlin, a versatile and modern programming language, offers developers a concise, safe, and interoperable coding experience. With features like null safety, extension functions, and coroutines, Kotlin enhances productivity and readability, making it an attractive choice for Android development and beyond. Whether you’re new to programming or an experienced developer, exploring Kotlin opens up a world of possibilities for building robust and expressive applications.

Mastering the Android Activity Lifecycle: A Comprehensive Guide

The Android Activity Lifecycle is a fundamental concept for Android developers. It defines how an Activity behaves during its lifecycle, from creation to destruction. Understanding the Activity Lifecycle is crucial for managing resources efficiently and delivering a smooth user experience. In this blog post, we’ll briefly introduce the different states an Activity can be in and the main callback methods associated with each state. Let’s dive in and explore this important aspect of Android app development!

Table of Contents

Send Us A Message