From 5b203394f74b0978bf1836f0f8a7488da9350d12 Mon Sep 17 00:00:00 2001 From: Hyunkuk Date: Mon, 2 Oct 2023 16:32:44 +0900 Subject: [PATCH] =?UTF-8?q?[feat]=20=EB=82=B4=EB=B6=80=20=EC=A0=80?= =?UTF-8?q?=EC=9E=A5=EC=86=8C=EC=97=90=20=EC=A0=80=EC=9E=A5=ED=95=98?= =?UTF-8?q?=EB=8A=94=20=EB=A1=9C=EC=A7=81=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mashup/twotoo/presenter/util/SaveImage.kt | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 presenter/src/main/java/com/mashup/twotoo/presenter/util/SaveImage.kt diff --git a/presenter/src/main/java/com/mashup/twotoo/presenter/util/SaveImage.kt b/presenter/src/main/java/com/mashup/twotoo/presenter/util/SaveImage.kt new file mode 100644 index 00000000..c9bd09b0 --- /dev/null +++ b/presenter/src/main/java/com/mashup/twotoo/presenter/util/SaveImage.kt @@ -0,0 +1,50 @@ +package com.mashup.twotoo.presenter.util + +import android.content.ContentValues +import android.content.Context +import android.graphics.Bitmap +import android.net.Uri +import android.os.Build +import android.os.Environment +import android.provider.MediaStore +import java.io.File +import java.io.FileOutputStream +import java.io.OutputStream + +fun saveBitmapToStorage( + context: Context, + bitmap: Bitmap, + title: String, + onSuccessToSave: () -> Unit, + onFailToSave: () -> Unit, + mimeType: String = "image/jpeg", + directory: String = Environment.DIRECTORY_PICTURES, + mediaContentUri: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI, +) { + val imageOutStream: OutputStream? + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + val values = ContentValues().apply { + put(MediaStore.Images.Media.DISPLAY_NAME, title) + put(MediaStore.Images.Media.MIME_TYPE, mimeType) + put(MediaStore.Images.Media.RELATIVE_PATH, directory) + } + + context.contentResolver.run { + val uri = this.insert(mediaContentUri, values) ?: run { + onFailToSave() + return + } + imageOutStream = openOutputStream(uri) ?: run { + onFailToSave() + return + } + } + } else { + val imagePath = Environment.getExternalStoragePublicDirectory(directory).absolutePath + val image = File(imagePath, title) + imageOutStream = FileOutputStream(image) + } + imageOutStream.use { bitmap.compress(Bitmap.CompressFormat.JPEG, 100, it) }.run { + onSuccessToSave() + } +}