안드로이드/코틀린

[Android Studio] 비트맵 사진을 갤러리에 저장하기 코틀린 Bitmap To Gallery Kotlin

eqrw105 2021. 4. 14. 21:51

[Android Studio] 비트맵 사진을 갤러리에 저장하기 코틀린 Bitmap To Gallery Kotlin

 

1. AndroidManifest.xml에 퍼미션 추가

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

 

2. AndroidManifest.xml -> application에 저장소 접근 허용 추가

    <application
        android:allowBackup="true"
        android:requestLegacyExternalStorage="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
    </application>

android:requestLegacyExternalStorage="true"

 

3. MainActivity -> 이미지 저장 이벤트 함수 정의

private fun saveImageToGallery(){
    button.setOnClickListener {
        //권한 체크
        if(!checkPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) ||
            !checkPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            return@setOnClickListener
        }
         //그림 저장
        if(!imageExternalSave(context, bitmap, context.getString(R.string.app_name))){
            Toast.makeText(context, "그림 저장을 실패하였습니다", Toast.LENGTH_SHORT).show()
            return@setOnClickListener
        }

		Toast.makeText(activity, "그림이 갤러리에 저장되었습니다", Toast.LENGTH_SHORT).show()
    }
}

 

4. 저장소 접근 함수 정의

fun imageExternalSave(context: Context, bitmap: Bitmap, path: String): Boolean {
        val state = Environment.getExternalStorageState()
        if (Environment.MEDIA_MOUNTED == state) {

            val rootPath =
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                    .toString()
            val dirName = "/" + path
            val fileName = System.currentTimeMillis().toString() + ".png"
            val savePath = File(rootPath + dirName)
            savePath.mkdirs()

            val file = File(savePath, fileName)
            if (file.exists()) file.delete()

            try {
                val out = FileOutputStream(file)
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)
                out.flush()
                out.close()

                //갤러리 갱신
                context.sendBroadcast(
                    Intent(
                        Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                        Uri.parse("file://" + Environment.getExternalStorageDirectory())
                    )
                )

                return true
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return false
    }

    fun checkPermission(activity: Activty, permission: String): Boolean {
        val permissionChecker =
            ContextCompat.checkSelfPermission(activity.applicationContext, permission)

        //권한이 없으면 권한 요청
        if (permissionChecker == PackageManager.PERMISSION_GRANTED) return true
        ActivityCompat.requestPermissions(activity, arrayOf(permission), mStorageExternalPermissionRequestCode)
        return false
    }