Android Bitmap与Base64互转

  • Post author:
  • Post category:其他


import android.graphics.Bitmap
import android.graphics.Bitmap.CompressFormat
import android.graphics.BitmapFactory
import android.util.Base64
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import java.io.ByteArrayOutputStream

/**
 * Bitmap converter
 *
 * Use [Base64] to covert a [Bitmap] to [String].
 *
 * With no [Exception] catching.
 */
object BitmapConverter {

    suspend fun convertBitmap2String(
        bitmap: Bitmap,
        format: CompressFormat = CompressFormat.PNG,
        quality: Int = 100
    ): String {
        val result = CoroutineScope(Dispatchers.IO).async {
            ByteArrayOutputStream().let { outputStream ->
                bitmap.compress(format, quality, outputStream)
                Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT)
            }
        }
        return result.await()
    }

    suspend fun convertString2Bitmap(bitmapStr: String): Bitmap {
        val result = CoroutineScope(Dispatchers.IO).async {
            val byteArray = Base64.decode(bitmapStr, Base64.DEFAULT)
            BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size)
        }
        return result.await()
    }
}



版权声明:本文为C_biubiubiu原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。