簡體   English   中英

如何在 kotlin 中將位圖轉換為字符串,將字符串轉換為位圖

[英]how can I convert Bitmap to String, String to bitmap in kotlin

我正在嘗試編寫我曾經在 Java 中使用的代碼,但它在 kotlin 中似乎不起作用。

// 在 Java 中

 public String BitMapToString(Bitmap bitmap){
     ByteArrayOutputStream baos=new  ByteArrayOutputStream();
     bitmap.compress(Bitmap.CompressFormat.PNG,100, baos);
     byte [] b=baos.toByteArray();
     String temp=Base64.encodeToString(b, Base64.DEFAULT);
     return temp;}

  // iam try like this
  // Base.encodeToString not work
  // that work is like this But request for Requires API O
  fun BitMapToString(bitmap: Bitmap): String {
     val base = ByteArrayOutputStream()
     bitmap.compress(Bitmap.CompressFormat.PNG, 100, base)
     val b = base.toByteArray()
     return Base64.getEncoder().encodeToString(b)
  }

如何在 kotlin 中從位圖轉換為字符串?

只需編寫以下代碼:

fun BitMapToString(bitmap: Bitmap): String {
    val baos = ByteArrayOutputStream()
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos)
    val b = baos.toByteArray()
    return Base64.encodeToString(b, Base64.DEFAULT)
}

這就是全部。 您只需首先將 base 64 字符串解碼為字節數組。:

val imageBytes = Base64.decode(string, 0)
val image = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)

我嘗試了顯示錯誤的代碼,它以這種方式工作

    @SuppressLint("NewApi")
    @TargetApi(Build.VERSION_CODES.O)
    @RequiresApi(Build.VERSION_CODES.O)
    fun BitMapToString(bitmap: Bitmap): String {
        val baos = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos)
        val b = baos.toByteArray()
        return Base64.getEncoder().encodeToString(b)
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM