如何return 相机中的图片

How to return the pic from Camera

我有以下代码,它打开相机 Intent 并允许我拍照并保存。 在我的 Activity layout 中,我有一个图像视图,我该如何对其进行编程,以便一旦相机捕捉到图片,相机意图就关闭,return 回到我的 activity,并且在图像视图中显示拍摄的照片?

// Androidanifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:dist="http://schemas.android.com/apk/distribution"
    package="hasan.tts_mobile">

    <dist:module dist:instant="true" />

    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-feature android:name="android.hardware.camera"
        android:required="true" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"></meta-data>
        </provider>

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

我的代码:

// MainActivity.kt
package hasan.tts_mobile

class MainActivity : AppCompatActivity() {
    private lateinit var uri: Uri
    val REQUEST_IMAGE_CAPTURE = 1
    lateinit var currentPhotoPath: String

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        btnCamera.setOnClickListener {
            if(isPermissionGranted(permission.CAMERA)) startCamera()
            else requestCameraPermission(this)
        }

    }

    private fun startCamera() {
        Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
            takePictureIntent.resolveActivity(packageManager)?.also {
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
            }
        }
    }

    @SuppressLint("MissingSuperCall")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            val imageBitmap = data!!.extras!!.get("data") as Bitmap
            imageView.setImageBitmap(imageBitmap)
        } 
    }

    override fun onRequestPermissionsResult(
        requestCode: Int, permissions: Array<String>,grantResults: IntArray) =
        onPermissionsRequestResult(this@MainActivity,
            requestCode, permissions, grantResults)

}

请求许可:

// CameraPermission.kt
object CameraPermission {
    fun requestCameraPermission(activity: AppCompatActivity) {
        Log.i(TAG, "CAMERA permission has NOT been granted. Requesting permission.")
        if (activity.shouldShowPermissionRationale(Manifest.permission.CAMERA)) {
            Log.i(TAG, "Displaying audio permission rationale to provide additional context.")
        } else {
                // Audio permission has not been granted yet. Request it directly.
                activity.requestPermission(Manifest.permission.CAMERA, REQUEST_CAMERA)
        }
    }
}

以下扩展以简化许可要求:

// 
fun AppCompatActivity.isPermissionGranted(permission: String) =
    ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED

fun AppCompatActivity.shouldShowPermissionRationale(permission: String) =
    ActivityCompat.shouldShowRequestPermissionRationale(this, permission)

fun AppCompatActivity.requestPermission(permission: String, requestId: Int) =
    ActivityCompat.requestPermissions(this, arrayOf(permission), requestId)

权限结果监听器:

// PermissionsRequestResult.kt
package hasan.tts_mobile.permissions

import android.content.Context
import android.content.pm.PackageManager
import android.widget.Toast
import hasan.tts_mobile.extensions.containsOnly


const val REQUEST_CAMERA = 0

object PermissionsRequestResult {
    fun onPermissionsRequestResult(context: Context, requestCode: Int, permissions: Array<String>,
                                            grantResults: IntArray) {

        when (requestCode) {
            REQUEST_CAMERA -> if (grantResults.containsOnly(PackageManager.PERMISSION_GRANTED)) {
                Toast.makeText(
                    context, "Camera permission is granted",
                    Toast.LENGTH_SHORT
                ).show()
                //   tts = TtsSpeaker(context, context)
            } else {
                Toast.makeText(
                    context, "Camera permission NOT granted",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }
}

containsOnly 是:

// CollectionExt.tk
package hasan.tts_mobile.extensions

fun IntArray.containsOnly(num: Int): Boolean = filter { it == num }.isNotEmpty()

xml/file_path.xml是:

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-files-path
        name="my_images" path="/Pictures"/>
</paths>

我的布局文件是:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.236"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.904" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="288dp"
        android:layout_height="401dp"
        android:layout_marginTop="96dp"
        android:contentDescription="@string/pic_desc"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@mipmap/ic_launcher" />

    <Button
        android:id="@+id/btnCamera"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="60dp"
        android:layout_marginBottom="60dp"
        android:text="@string/take_pic"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

我需要在 activity?

的图像视图中显示拍摄的照片以代替 Android 徽标

在onActivityResult()中

val imgUri = data?.data
imageView.setImageURI(imgUri) 

如果使用滑行

Glide.with(this).load(imgUri).placeholder(R.drawable.ic_placeholder).into(this)

首先,使用 Intent(MediaStore.ACTION_IMAGE_CAPTURE)

拍摄图像时无需询问CAMERA permission

试试这个代码

Declare below variables

private val CONTENT_REQUEST = 123
private var output: File? = null
var outPutFileUri: Uri? = null

Take picture using below code

    btnTakePhoto.setOnClickListener {
         val fileName = System.currentTimeMillis().toString() + ".jpeg"
         output = File(
             mContext?.getExternalFilesDir(Environment.DIRECTORY_PICTURES),
             fileName
         )
         val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
         outPutFileUri = mContext?.let { it1 ->
             FileProvider.getUriForFile(
                 it1,
                 BuildConfig.APPLICATION_ID,
                 output!!
             )
         }
         intent.putExtra(MediaStore.EXTRA_OUTPUT, outPutFileUri)
         startActivityForResult(intent, CONTENT_REQUEST)
        
    }

set image in your image view using below code

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    if (requestCode == CONTENT_REQUEST) {
        if (resultCode == Activity.RESULT_OK) {
            userIMG.setImageURI(outPutFileUri)
        }
    }
}

注意

don't forget to add provider inside <application of manifest file

you need to add your package name inside android:authorities="

    <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="hasan.tts_mobile"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths"/>
    </provider>

或: android:authorities="${applicationId}",不是原代码中的"${applicationId}.fileprovider"