import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL
fun imgToBase64(path: String): String {
val data: ByteArray? = null
var `in`: InputStream? = null
var out: ByteArrayOutputStream? = null
try {
val url = URL(path)
val connection: HttpURLConnection = url.openConnection() as HttpURLConnection
connection.setRequestMethod("GET")
connection.setConnectTimeout(5000)
connection.setReadTimeout(5000)
`in` = connection.getInputStream()
out = ByteArrayOutputStream()
val b = ByteArray(1024)
var len = 0
while (`in`.read(b).also { len = it } != -1) {
out.write(b, 0, len)
}
} catch (e: Exception) {
e.printStackTrace()
} finally {
try {
`in`?.close()
} catch (e: IOException) {
e.stackTrace
}
}
System.out.println("转换后的图片大小:" + out!!.toByteArray().size / 1024)
val base = BASE64Encoder()
return base.encode(out.toByteArray()).replace("\n", "").replace("\r", "");
}
|