【问题标题】:How to convert base64 string into image in kotlin android如何在kotlin android中将base64字符串转换为图像
【发布时间】:2020-03-16 05:38:41
【问题描述】:

我有一个表示位图图像的 Base64 字符串。

我需要再次将该字符串转换为位图图像,以便在我的 Android 应用中的 ImageView 上使用它

怎么做?

【问题讨论】:

标签: android android-studio kotlin base64


【解决方案1】:

根据上面的答案,我把它做成了一个函数。

科特林: 你可以创建一个这样的函数

 fun decodePicString (encodedString: String): Bitmap {

    val imageBytes = Base64.decode(encodedString, Base64.DEFAULT)
    val decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)

    return decodedImage
}    

然后调用它并将其设置为您的 imgView 像这样:

val mImgView = findViewById<ImageView>(R.id.imageView)
mImageView.setImageBitmap(decodePicString(your encoded string for the picture))

【讨论】:

  • 在问题中,它有相同的答案。所以答案应该删除。
【解决方案2】:

你可以使用android方法

这里imageString 是您的base64String 图像。

这里是java代码:

byte[] decodedByte = Base64.decode(imageString, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(decodedByte, 0, decodedString.length); 

这里是 kotlin 代码:

val decodedByte = Base64.decode(imageString, Base64.DEFAULT)
val bitmap = BitmapFactory.decodeByteArray(decodedByte, 0, decodedString.length) 

之后,您可以将其设置到图像视图中

yourimage.setImageBitmap(bitmap);

【讨论】:

  • 这看起来不像kotlin
  • @VladyslavMatviienko 如果将代码粘贴到 kotlin 中,它会自动转换为 kotlin 代码。但我也添加了 kotlin 的代码。
  • 这个 kotlin 代码对我不起作用,直到我将 BitmapFactory.decodeByteArray(decodedByte, 0, decodedString.length) 更改为 BitmapFactory.decodeByteArray(decodedByte, 0, decodedString.size)。 decodedString 没有“长度”方法,只有“大小”方法。更改后,一切都像魅力一样,所以谢谢你的代码。
【解决方案3】:

您可以使用此代码进行解码:-

val imageBytes = Base64.decode(base64String, Base64.DEFAULT)
val decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length)
imageView.setImageBitmap(decodedImage)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    • 1970-01-01
    • 2018-09-07
    • 2014-07-21
    • 1970-01-01
    相关资源
    最近更新 更多