Android Base64 轉(zhuǎn)圖片保存本地

Base64 轉(zhuǎn)換 Bitmap

    fun convertBase64ToPic(base64: String): Bitmap? {
        var value = base64
        if (base64.contains(",")) {
            value = base64.split(",")[1]
        }
        val decode = Base64.decode(value, Base64.DEFAULT)
        return BitmapFactory.decodeByteArray(decode, 0, decode.size)
    }

Bitmap 保存到本地相冊院领,新建 ImageExt.kt 文件

private const val TAG = "ImageExt"

private val ALBUM_DIR = Environment.DIRECTORY_DCIM

private class OutputFileTaker(var file: File? = null)

/**
 * 復(fù)制圖片文件到相冊的Pictures文件夾
 *
 * @param context 上下文
 * @param fileName 文件名吸申。 需要攜帶后綴
 * @param relativePath 相對于Pictures的路徑
 */
fun File.copyToAlbum(context: Context, fileName: String, relativePath: String?): Uri? {
    if (!this.canRead() || !this.exists()) {
        Log.w(TAG, "check: read file error: $this")
        return null
    }
    return this.inputStream().use {
        it.saveToAlbum(context, fileName, relativePath)
    }
}

/**
 * 保存圖片Stream到相冊的Pictures文件夾
 *
 * @param context 上下文
 * @param fileName 文件名司抱。 需要攜帶后綴
 * @param relativePath 相對于Pictures的路徑
 */
fun InputStream.saveToAlbum(context: Context, fileName: String, relativePath: String?): Uri? {
    val resolver = context.contentResolver
    val outputFile = OutputFileTaker()
    val imageUri = resolver.insertMediaImage(fileName, relativePath, outputFile)
    if (imageUri == null) {
        Log.w(TAG, "insert: error: uri == null")
        return null
    }

    (imageUri.outputStream(resolver) ?: return null).use { output ->
        this.use { input ->
            input.copyTo(output)
            imageUri.finishPending(context, resolver, outputFile.file)
        }
    }
    return imageUri
}

/**
 * 保存Bitmap到相冊的Pictures文件夾
 *
 * https://developer.android.google.cn/training/data-storage/shared/media
 *
 * @param context 上下文
 * @param fileName 文件名丽柿。 需要攜帶后綴
 * @param relativePath 相對于Pictures的路徑
 * @param quality 質(zhì)量
 */
fun Bitmap.saveToAlbum(
    context: Context,
    fileName: String,
    relativePath: String? = null,
    quality: Int = 75,
): Uri? {
    // 插入圖片信息
    val resolver = context.contentResolver
    val outputFile = OutputFileTaker()
    val imageUri = resolver.insertMediaImage(fileName, relativePath, outputFile)
    if (imageUri == null) {
        Log.w(TAG, "insert: error: uri == null")
        return null
    }

    // 保存圖片
    (imageUri.outputStream(resolver) ?: return null).use {
        val format = fileName.getBitmapFormat()
        this@saveToAlbum.compress(format, quality, it)
        imageUri.finishPending(context, resolver, outputFile.file)
    }
    return imageUri
}

private fun Uri.outputStream(resolver: ContentResolver): OutputStream? {
    return try {
        resolver.openOutputStream(this)
    } catch (e: FileNotFoundException) {
        Log.e(TAG, "save: open stream error: $e")
        null
    }
}

private fun Uri.finishPending(
    context: Context,
    resolver: ContentResolver,
    outputFile: File?,
) {
    val imageValues = ContentValues()
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
        if (outputFile != null) {
            imageValues.put(MediaStore.Images.Media.SIZE, outputFile.length())
        }
        resolver.update(this, imageValues, null, null)
        // 通知媒體庫更新
        val intent = Intent(@Suppress("DEPRECATION") Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, this)
        context.sendBroadcast(intent)
    } else {
        // Android Q添加了IS_PENDING狀態(tài),為0時其他應(yīng)用才可見
        imageValues.put(MediaStore.Images.Media.IS_PENDING, 0)
        resolver.update(this, imageValues, null, null)
    }
}

private fun String.getBitmapFormat(): Bitmap.CompressFormat {
    val fileName = this.lowercase()
    return when {
        fileName.endsWith(".png") -> Bitmap.CompressFormat.PNG
        fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") -> Bitmap.CompressFormat.JPEG
        fileName.endsWith(".webp") -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
            Bitmap.CompressFormat.WEBP_LOSSLESS else Bitmap.CompressFormat.WEBP
        else -> Bitmap.CompressFormat.PNG
    }
}

private fun String.getMimeType(): String? {
    val fileName = this.lowercase()
    return when {
        fileName.endsWith(".png") -> "image/png"
        fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") -> "image/jpeg"
        fileName.endsWith(".webp") -> "image/webp"
        fileName.endsWith(".gif") -> "image/gif"
        else -> null
    }
}

/**
 * 插入圖片到媒體庫
 */
private fun ContentResolver.insertMediaImage(
    fileName: String,
    relativePath: String?,
    outputFileTaker: OutputFileTaker? = null,
): Uri? {
    // 圖片信息
    val imageValues = ContentValues().apply {
        val mimeType = fileName.getMimeType()
        if (mimeType != null) {
            put(MediaStore.Images.Media.MIME_TYPE, mimeType)
        }
        val date = System.currentTimeMillis() / 1000
        put(MediaStore.Images.Media.DATE_ADDED, date)
        put(MediaStore.Images.Media.DATE_MODIFIED, date)
    }
    // 保存的位置
    val collection: Uri
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        val path = if (relativePath != null) "$ALBUM_DIR/${relativePath}" else ALBUM_DIR
        imageValues.apply {
            put(MediaStore.Images.Media.DISPLAY_NAME, fileName)
            put(MediaStore.Images.Media.RELATIVE_PATH, path)
            put(MediaStore.Images.Media.IS_PENDING, 1)
        }
        collection = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
        // 高版本不用查重直接插入妇垢,會自動重命名
    } else {
        // 老版本
        val pictures =
            @Suppress("DEPRECATION") Environment.getExternalStoragePublicDirectory(ALBUM_DIR)
        val saveDir = if (relativePath != null) File(pictures, relativePath) else pictures

        if (!saveDir.exists() && !saveDir.mkdirs()) {
            Log.e(TAG, "save: error: can't create Pictures directory")
            return null
        }

        // 文件路徑查重妓笙,重復(fù)的話在文件名后拼接數(shù)字
        var imageFile = File(saveDir, fileName)
        val fileNameWithoutExtension = imageFile.nameWithoutExtension
        val fileExtension = imageFile.extension

        var queryUri = this.queryMediaImage28(imageFile.absolutePath)
        var suffix = 1
        while (queryUri != null) {
            val newName = fileNameWithoutExtension + "(${suffix++})." + fileExtension
            imageFile = File(saveDir, newName)
            queryUri = this.queryMediaImage28(imageFile.absolutePath)
        }

        imageValues.apply {
            put(MediaStore.Images.Media.DISPLAY_NAME, imageFile.name)
            // 保存路徑
            val imagePath = imageFile.absolutePath
            Log.v(TAG, "save file: $imagePath")
            put(@Suppress("DEPRECATION") MediaStore.Images.Media.DATA, imagePath)
        }
        outputFileTaker?.file = imageFile// 回傳文件路徑,用于設(shè)置文件大小
        collection = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
    }
    // 插入圖片信息
    return this.insert(collection, imageValues)
}

/**
 * Android Q以下版本幅狮,查詢媒體庫中當(dāng)前路徑是否存在
 * @return Uri 返回null時說明不存在募强,可以進(jìn)行圖片插入邏輯
 */
private fun ContentResolver.queryMediaImage28(imagePath: String): Uri? {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) return null

    val imageFile = File(imagePath)
    if (imageFile.canRead() && imageFile.exists()) {
        Log.v(TAG, "query: path: $imagePath exists")
        // 文件已存在株灸,返回一個file://xxx的uri
        return Uri.fromFile(imageFile)
    }
    // 保存的位置
    val collection = MediaStore.Images.Media.EXTERNAL_CONTENT_URI

    // 查詢是否已經(jīng)存在相同圖片
    val query = this.query(
        collection,
        arrayOf(MediaStore.Images.Media._ID, @Suppress("DEPRECATION") MediaStore.Images.Media.DATA),
        "${@Suppress("DEPRECATION") MediaStore.Images.Media.DATA} == ?",
        arrayOf(imagePath), null
    )
    query?.use {
        while (it.moveToNext()) {
            val idColumn = it.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
            val id = it.getLong(idColumn)
            val existsUri = ContentUris.withAppendedId(collection, id)
            Log.v(TAG, "query: path: $imagePath exists uri: $existsUri")
            return existsUri
        }
    }
    return null
}

用法

          val ioResult = withContext(Dispatchers.IO) {
                    val bitmap = FileUtil.convertBase64ToPic(base64Data)
                    var result = false
                    bitmap?.let {
                        val uri = it.saveToAlbum(context, fileName = "${System.currentTimeMillis()}.png")
                        result = uri != null
                    }
                    result
                }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市擎值,隨后出現(xiàn)的幾起案子慌烧,更是在濱河造成了極大的恐慌,老刑警劉巖鸠儿,帶你破解...
    沈念sama閱讀 221,820評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件屹蚊,死亡現(xiàn)場離奇詭異,居然都是意外死亡进每,警方通過查閱死者的電腦和手機汹粤,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,648評論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來田晚,“玉大人嘱兼,你說我怎么就攤上這事∠屯剑” “怎么了芹壕?”我有些...
    開封第一講書人閱讀 168,324評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長接奈。 經(jīng)常有香客問我踢涌,道長,這世上最難降的妖魔是什么序宦? 我笑而不...
    開封第一講書人閱讀 59,714評論 1 297
  • 正文 為了忘掉前任睁壁,我火速辦了婚禮,結(jié)果婚禮上挨厚,老公的妹妹穿的比我還像新娘堡僻。我一直安慰自己,他們只是感情好疫剃,可當(dāng)我...
    茶點故事閱讀 68,724評論 6 397
  • 文/花漫 我一把揭開白布钉疫。 她就那樣靜靜地躺著,像睡著了一般巢价。 火紅的嫁衣襯著肌膚如雪牲阁。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,328評論 1 310
  • 那天壤躲,我揣著相機與錄音城菊,去河邊找鬼。 笑死碉克,一個胖子當(dāng)著我的面吹牛凌唬,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播漏麦,決...
    沈念sama閱讀 40,897評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼客税,長吁一口氣:“原來是場噩夢啊……” “哼况褪!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起更耻,我...
    開封第一講書人閱讀 39,804評論 0 276
  • 序言:老撾萬榮一對情侶失蹤测垛,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后秧均,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體食侮,經(jīng)...
    沈念sama閱讀 46,345評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,431評論 3 340
  • 正文 我和宋清朗相戀三年目胡,在試婚紗的時候發(fā)現(xiàn)自己被綠了锯七。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,561評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡讶隐,死狀恐怖起胰,靈堂內(nèi)的尸體忽然破棺而出久又,到底是詐尸還是另有隱情巫延,我是刑警寧澤,帶...
    沈念sama閱讀 36,238評論 5 350
  • 正文 年R本政府宣布地消,位于F島的核電站炉峰,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏脉执。R本人自食惡果不足惜疼阔,卻給世界環(huán)境...
    茶點故事閱讀 41,928評論 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望半夷。 院中可真熱鬧婆廊,春花似錦、人聲如沸巫橄。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,417評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽湘换。三九已至宾舅,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間彩倚,已是汗流浹背筹我。 一陣腳步聲響...
    開封第一講書人閱讀 33,528評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留帆离,地道東北人蔬蕊。 一個月前我還...
    沈念sama閱讀 48,983評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像哥谷,于是被迫代替她去往敵國和親岸夯。 傳聞我的和親對象是個殘疾皇子概而,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,573評論 2 359

推薦閱讀更多精彩內(nèi)容