Single intent to let user take picture OR pick image from gallery in Android

前端 未结 4 428
广开言路
广开言路 2020-12-07 08:05

I\'m developing an app for Android 2.1 upwards. I want to enable my users to select a profile picture within my app (I\'m not using the contacts framework).

The id

4条回答
  •  臣服心动
    2020-12-07 08:39

    My Answer is almost identical to @Macarse solution but I also add an additional intent to show gallery apps (Ex: Google Photos) and is written in Kotlin:

    val REQUEST_CODE_GET_IMAGE = 101
    
    private fun addProfileImage() {
        val pickImageFileIntent = Intent()
        pickImageFileIntent.type = "image/*"
        pickImageFileIntent.action = Intent.ACTION_GET_CONTENT
    
        val pickGalleryImageIntent = Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
    
        val captureCameraImageIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
    
        val pickTitle = "Capture from camera or Select from gallery the Profile photo"
        val chooserIntent = Intent.createChooser(pickImageFileIntent, pickTitle)
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, arrayOf(captureCameraImageIntent, pickGalleryImageIntent))
        startActivityForResult(chooserIntent, REQUEST_CODE_GET_IMAGE)
    }
    

    Extract image from result intent:

    private var imageTempFile: File? = null
    private var imageMimeType: String? = null
    
    private fun extractImage(intent: Intent?) {
        val imageUri = intent?.data
        imageUri?.let {
            Glide.with(this)
                    .load(imageUri)
                    .into(profileImageCiv)
            imageTempFile = MediaUtils.copyContentFromUriToCacheFile(this, imageUri, Settings.DIRECTORY_CACHE_TEMP_PROFILE_IMAGE)
            imageMimeType = MediaUtils.getMimeType(this, imageUri)
        } ?: run {
            intent?.extras?.get("data")?.let { bitmap ->    // Bitmap was returned as raw bitmap
                Glide.with(this)
                        .load(bitmap)
                        .into(profileImageCiv)
                imageTempFile = MediaUtils.writeBitmapToCacheFile(this, bitmap as Bitmap, Settings.DIRECTORY_CACHE_TEMP_PROFILE_IMAGE)
                imageMimeType = "image/jpeg"    // The bitmap was compressed as JPEG format. The bitmap itself doesn't have any format associated to it
            } ?: run {
                imageTempFile = null
                imageMimeType = null
                Log.e("Intent data is null.")
                Log.d("Error during photo selection")
            }
        }
    }
    

提交回复
热议问题