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

How does data persistence work in Android?

Data persistence in Android is the ability to save data to the device so that it can be accessed later, even if the app is closed or the device is restarted. There are several ways to achieve data persistence in Android

Fragments and Activities: Two Pillars of Android Development

Fragments and Activities are both important components of Android development. Fragments are a good choice for creating reusable and dynamic UIs, while Activities are a good choice for managing the lifecycle of an app’s UI and implementing core features.

Table of Contents

Send Us A Message