react-native-vision-camera/android/src/main/java/com/mrousavy/camera/CameraView+TakeSnapshot.kt

43 lines
1.5 KiB
Kotlin
Raw Normal View History

2021-02-19 12:41:49 -07:00
package com.mrousavy.camera
2021-02-19 08:28:14 -07:00
import android.graphics.Bitmap
import androidx.exifinterface.media.ExifInterface
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.ReadableMap
import com.facebook.react.bridge.WritableMap
import com.mrousavy.camera.utils.buildMetadataMap
2021-02-19 08:28:14 -07:00
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream
suspend fun CameraView.takeSnapshot(options: ReadableMap): WritableMap = coroutineScope {
val bitmap = this@takeSnapshot.previewView.bitmap ?: throw CameraNotReadyError()
2021-02-19 08:28:14 -07:00
val quality = if (options.hasKey("quality")) options.getInt("quality") else 100
2021-02-19 08:28:14 -07:00
val file: File
val exif: ExifInterface
@Suppress("BlockingMethodInNonBlockingContext")
withContext(Dispatchers.IO) {
file = File.createTempFile("mrousavy", ".jpg", context.cacheDir).apply { deleteOnExit() }
FileOutputStream(file).use { stream ->
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream)
2021-02-19 08:28:14 -07:00
}
exif = ExifInterface(file)
}
2021-02-19 08:28:14 -07:00
val map = Arguments.createMap()
map.putString("path", file.absolutePath)
map.putInt("width", bitmap.width)
map.putInt("height", bitmap.height)
map.putBoolean("isRawPhoto", false)
2021-02-19 08:28:14 -07:00
val skipMetadata = if (options.hasKey("skipMetadata")) options.getBoolean("skipMetadata") else false
val metadata = if (skipMetadata) null else exif.buildMetadataMap()
map.putMap("metadata", metadata)
2021-02-19 08:28:14 -07:00
return@coroutineScope map
2021-02-19 08:28:14 -07:00
}