Android

Android 內建相機 圖片儲存&圖片讀取

Android 內建相機 圖片儲存&圖片讀取

  1. 機身內部&機身外部
  2. 外部儲存

1.機身內部&機身外部

a.創建FileProvider (xml>file_provider.xml)

<paths>
    <external-path name="external-path" path="."/>
    <external-cache-path name="external-cache-path" path="."/>
    <files-path name="files-path" path="."/>
    <cache-path name="cache-path" path="."/>
</paths>

b.Manifests聲明Provider

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

c.調用內建相機並設定Uri

val file = File(cacheDir, "${System.currentTimeMillis()}photo.jpg")
val imgUri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", file)

val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri)
startActivityForResult(intent, 0)

d.顯示圖片(兩種)

imageView.setImageURI(imgUri)
val bitmap = BitmapFactory.decodeFile(file.absolutePath)
imageView.setImageBitmap(bitmap)

2.外部儲存

a.調用內建相機並設定Uri

val contentValues = ContentValues()

contentValues.put(
    MediaStore.Images.ImageColumns.DISPLAY_NAME,
    "${System.currentTimeMillis()}photo.jpg"
)
contentValues.put(MediaStore.Images.ImageColumns.MIME_TYPE, "image/jpeg")
imgUri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)!!

val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri)
startActivityForResult(intent, 0)

b.顯示圖片(兩種)

imageView.setImageURI(imgUri)
val file = uriToFileApiQ(imgUri)
val bitmap = BitmapFactory.decodeFile(file?.absolutePath)
imageView.setImageBitmap(bitmap)

@RequiresApi(Build.VERSION_CODES.Q)
private fun uriToFileApiQ(uri: Uri): File? {
    var file: File? = null
    if (uri.scheme == ContentResolver.SCHEME_FILE) {
        file = File(uri.toString())
    } else if (uri.scheme == ContentResolver.SCHEME_CONTENT) {
        val cursor: Cursor? = contentResolver.query(uri, null, null, null, null)
        cursor?.run {
            if (moveToFirst()) {
                val displayName: String =
                    getString(getColumnIndex(OpenableColumns.DISPLAY_NAME))
                try {
                    val `is`: InputStream = contentResolver.openInputStream(uri)!!
                    val cache = File(
                        filesDir.absolutePath,
                        ((Math.random() + 1) * 1000).roundToInt().toString() + displayName
                    )
                    val fos = FileOutputStream(cache)
                    FileUtils.copy(`is`, fos)
                    file = cache
                    fos.close()
                    `is`.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
            cursor.close()
        }
    }
    return file
}

發表迴響