Capture Image from Camera and Display in Activity

前端 未结 16 1059
悲&欢浪女
悲&欢浪女 2020-11-21 06:43

I want to write a module where on a click of a button the camera opens and I can click and capture an image. If I don\'t like the image I can delete it and click one more i

16条回答
  •  Happy的楠姐
    2020-11-21 07:09

    Please, follow this example with this implementation by using Kotlin and Andoirdx support:

    button1.setOnClickListener{
            file = getPhotoFile()
            val uri: Uri = FileProvider.getUriForFile(applicationContext, "com.example.foto_2.filrprovider", file!!)
            captureImage.putExtra(MediaStore.EXTRA_OUTPUT, uri)
    
            val camaraActivities: List = applicationContext.getPackageManager().queryIntentActivities(captureImage, PackageManager.MATCH_DEFAULT_ONLY)
    
            for (activity in camaraActivities) {
                applicationContext.grantUriPermission(activity.activityInfo.packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
            }
    
            startActivityForResult(captureImage, REQUEST_PHOTO)
        }
    

    And the activity result:

    if (requestCode == REQUEST_PHOTO) {
            val uri = FileProvider.getUriForFile(applicationContext, "com.example.foto_2.filrprovider", file!!)
            applicationContext.revokeUriPermission(uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
            imageView1.viewTreeObserver.addOnGlobalLayoutListener {
                width = imageView1.width
                height = imageView1.height
                imageView1.setImageBitmap(getScaleBitmap(file!!.path , width , height))
            }
            if(width!=0&&height!=0){
                imageView1.setImageBitmap(getScaleBitmap(file!!.path , width , height))
            }else{
                val size = Point()
                this.windowManager.defaultDisplay.getSize(size)
                imageView1.setImageBitmap(getScaleBitmap(file!!.path , size.x , size.y))
            }
    
        }
    

    You can get more detail in https://github.com/joelmmx/take_photo_kotlin.git

    I hope it helps you!

提交回复
热议问题