我正在尝试编写我以前在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中将位图转换为String?
答案 0 :(得分:0)
就是这样。您只需要将基本64字符串首先解码为字节数组。:
val imageBytes = Base64.decode(string, 0)
val image = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)
答案 1 :(得分:0)
只需编写此代码:
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)
}
答案 2 :(得分:-1)
我尝试了显示为错误的代码,并以此方式工作
@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)
}