From fc0e2bf34b9cb35b75b0da1330448fa96cee6acb Mon Sep 17 00:00:00 2001 From: Vojtech Novak Date: Fri, 1 Sep 2023 19:41:42 +0200 Subject: [PATCH] fix: Fix `savePhotoToFile()` sometimes writing empty files (#1746) --- package/android/.editorconfig | 1 + .../mrousavy/camera/CameraView+TakePhoto.kt | 23 +++++++++++-------- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/package/android/.editorconfig b/package/android/.editorconfig index 768db0c..69a66f9 100644 --- a/package/android/.editorconfig +++ b/package/android/.editorconfig @@ -1,5 +1,6 @@ [*.{kt,kts}] indent_size=2 +indent_style=space insert_final_newline=true max_line_length=off disabled_rules=no-wildcard-imports diff --git a/package/android/src/main/java/com/mrousavy/camera/CameraView+TakePhoto.kt b/package/android/src/main/java/com/mrousavy/camera/CameraView+TakePhoto.kt index bff9bd6..6ff53ba 100644 --- a/package/android/src/main/java/com/mrousavy/camera/CameraView+TakePhoto.kt +++ b/package/android/src/main/java/com/mrousavy/camera/CameraView+TakePhoto.kt @@ -64,15 +64,22 @@ suspend fun CameraView.takePhoto(optionsMap: ReadableMap): WritableMap { } } -private fun writeImageToStream(imageBytes: ByteArray, stream: OutputStream, isMirrored: Boolean) { - if (isMirrored) { +private fun writePhotoToFile(photo: CameraSession.CapturedPhoto, file: File) { + val byteBuffer = photo.image.planes[0].buffer + if (photo.isMirrored) { + val imageBytes = ByteArray(byteBuffer.remaining()).apply { byteBuffer.get(this) } val bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size) val matrix = Matrix() matrix.preScale(-1f, 1f) - val processedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, false) - processedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream) + val processedBitmap = + Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, false) + FileOutputStream(file).use { stream -> + processedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream) + } } else { - stream.write(imageBytes) + val channel = FileOutputStream(file).channel + channel.write(byteBuffer) + channel.close() } } @@ -83,12 +90,8 @@ private suspend fun savePhotoToFile(context: Context, when (photo.format) { // When the format is JPEG or DEPTH JPEG we can simply save the bytes as-is ImageFormat.JPEG, ImageFormat.DEPTH_JPEG -> { - val buffer = photo.image.planes[0].buffer - val bytes = ByteArray(buffer.remaining()).apply { buffer.get(this) } val file = createFile(context, ".jpg") - FileOutputStream(file).use { stream -> - writeImageToStream(bytes, stream, photo.isMirrored) - } + writePhotoToFile(photo, file) return@withContext file.absolutePath }