How to pick image for crop from camera or gallery in Android 7.0?

后端 未结 9 2277
礼貌的吻别
礼貌的吻别 2020-12-01 04:56

Pick image for crop from gallery and camera it\'s done for below Android 7.0 but in Android Nought it crashes in camera. I use fileprovider for it but doesn\'t work.

9条回答
  •  盖世英雄少女心
    2020-12-01 05:28

    Following solution works for me. I've tested with Gallery, Google drive, Photos etc.

    Sample is in Kotlin language.

    ImagePickUtils.kt

    fun getImageUri(context: Context, contentURI: String): Uri {
        var conUri = Uri.parse(contentURI)
        var filePath = ""
        if (DocumentsContract.isDocumentUri(context, conUri)) {
            val wholeID = DocumentsContract.getDocumentId(conUri)
    
            // Split at colon, use second item in the array
            val id = wholeID.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[1]
    
            val column = arrayOf(MediaStore.Images.Media.DATA)
    
            // where id is equal to
            val sel = MediaStore.Images.Media._ID + "=?"
    
            val cursor = context.contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    column, sel, arrayOf(id), null) ?: return conUri
    
            val columnIndex = cursor.getColumnIndex(column[0])
    
            if (cursor.moveToFirst()) {
                filePath = cursor.getString(columnIndex)
            }
            cursor.close()
    
            if (filePath.isNotEmpty()) {
                filePath = filePath.replace(" ".toRegex(), "%20")
                conUri = Uri.parse("file://$filePath")
            }
        }
        return conUri
    }
    

    onActivityResult of Activity / Fragment:

    if (data != null) {
        val imagePath: Uri
        if (data.data != null) {
               val mImageUri = data.data
               imagePath = getImageUri(this@HomeActivity, mImageUri.toString())
               Log.i(TAG+" Image actual path", imagePath.toString())
        }
    }
    

    Hope this would help you.

提交回复
热议问题