在android上传图片的时候,有时候需要把图片转换为base64编码上传到服务器
开始的时候使用以下方法
fun imageToBase64(path: String): String? {
if (TextUtils.isEmpty(path)) {
return null
}
var `is`: InputStream? = null
var data: ByteArray? = null
var result: String? = null
try {
`is` = FileInputStream(path)
//创建一个字符流大小的数组。
data = ByteArray(`is`!!.available())
//写入数组
`is`!!.read(data)
//用默认的编码格式进行编码
result = String(Base64.encode(data, Base64.NO_WRAP))
} catch (e: IOException) {
e.printStackTrace()
Log.e("123", e.toString())
} finally {
if (null != `is`) {
try {
`is`!!.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
return result
}
这个方法部分图片不成功,部分图片可以显示,不稳定。
最后采用下面的方法
fun UrlToBase64(imgUrl: String): String {
val bm = getSmallBitmap(imgUrl)
val baos = ByteArrayOutputStream()
bm.compress(Bitmap.CompressFormat.JPEG, 40, baos)
val b = baos.toByteArray()
return Base64.encodeToString(b, Base64.DEFAULT)
}
// 根据路径获得图片并压缩,返回bitmap用于显示
fun getSmallBitmap(filePath: String): Bitmap {
val options = BitmapFactory.Options()
options.inJustDecodeBounds = true
BitmapFactory.decodeFile(filePath, options)
// Calculate inSampleSize
// options.inSampleSize = calculateInSampleSize(options, 800, 480)
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false
return BitmapFactory.decodeFile(filePath, options)
}
先把路径转换为bitmap,之后在转化为base64,解决此问题