[英]how can I convert Bitmap to String, String to bitmap in kotlin
I am trying to write the code I used to use in Java, but it does not seem to work in kotlin.我正在尝试编写我曾经在 Java 中使用的代码,但它在 kotlin 中似乎不起作用。
// in java // 在 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)
}
how can I convert from bitmap to String in kotlin?如何在 kotlin 中从位图转换为字符串?
Just write this code:只需编写以下代码:
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)
}
That is all.这就是全部。 You just have to decode the base 64 string first into a byte array.:您只需首先将 base 64 字符串解码为字节数组。:
val imageBytes = Base64.decode(string, 0)
val image = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)
I tried the code that showed as wrong and it worked that way我尝试了显示错误的代码,它以这种方式工作
@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.