App/개발

[안드로이드] 비트맵 파일을 파일 타입으로 변환하기 (bitmap to file)

Say simple 2020. 11. 19. 15:52
728x90
반응형

 

비트맵을 파일로 변환하는 코드입니다.

    fun saveBitmapToFileCache(bitmap: Bitmap, strFilePath: String, fileName:String) {
    	val file = File(strFilePath)
    	if (!file.exists()) file.mkdirs()
    	
        val fileCacheItem = File(strFilePath + fileName)
        var out: OutputStream? = null

        try {
            fileCacheItem.createNewFile()
            out = FileOutputStream(fileCacheItem)
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            try {
                out?.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }

파일 객체를 생성한 후 파일 객체가 가르키는 위치에 디렉토리가 없으면 디렉토리를 생성합니다.

디렉토리 안에 새로운 파일을 만든 후 그 파일에 bitmap을 outputStream으로 작성합니다.

728x90
반응형