开发学习记录
1、调用相机拍照
private fun takePhotoThumb() {Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->takePictureIntent.resolveActivity(packageManager)?.also {startActivityForResult(takePictureIntent, requestTakeThumbCode)}}}
接收返回的照片缩略图
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {super.onActivityResult(requestCode, resultCode, data)if (resultCode == RESULT_OK) {when (requestCode) {requestTakeThumbCode -> {val bitmap = data?.extras?.get("data") as Bitmapimg.setImageBitmap(bitmap)}}}}
此方法获取到的是拍照的缩略图
2、相机拍照,并返回照片路径
val fileProvider="com.example.myapplication.fileProvider"
private fun takePhoto() {Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePhotoIntent ->takePhotoIntent.resolveActivity(packageManager)?.also {val photoFile = createImgFile()photoFile?.also {val uriForFile = FileProvider.getUriForFile(this,fileProvider,it)takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriForFile)startActivityForResult(takePhotoIntent, requestTakePhoto)}}}}
fileProvider 名字需要跟后面清单文件中 authorities 的值相同
createImgFile()
lateinit var currentPhotoPath: Stringprivate fun createImgFile(): File {val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())val storeDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES)return File.createTempFile("JPEG_${timeStamp}", ".jpg", storeDir).apply {currentPhotoPath = absolutePath}}
使用此方法可以获取拍摄的照片路径,但需要在清单文件中加入一些配置
<application...<providerandroid:name="androidx.core.content.FileProvider"android:authorities="com.example.myapplication.fileProvider"android:exported="false"android:grantUriPermissions="true"><meta-dataandroid:name="android.support.FILE_PROVIDER_PATHS"android:resource="@xml/file_paths"></meta-data></provider></application>
注意 :android:authorities="com.example.myapplication.fileProvider" 此处value 需要换成自己的
@xml/file_paths :在目录res 下创建 xml 文件夹 ,添加 file_paths.xml文件
<?xml version="1.0" encoding="utf-8"?>
<paths><external-files-pathname="my_images"path="." />
</paths>
留言跟我交流(* ̄︶ ̄)
参考文档 拍照 | Android 开发者 | Android Developers