Android:使用HTML在webView中显示存储中的图像

时间:2018-04-24 17:19:33

标签: android webview kotlin

我有一个显示html的webview,我有一个不希望在这里显示的URI图像是我的代码:

<td class="title">
       <img src="#LOGO#" style="width:15%; max-width:300px;"/>
</td>

这是我的代码:

str = str.replace("#LOGO#", Uri.parse(myStringPath).toString())

图片未显示

1 个答案:

答案 0 :(得分:2)

你必须将图像转换为位图,然后你才能在Html中显示位图:

var logoImage: String? = null
    try {
        val imageUri = Uri.parse(myStringPath)
        var imageStream: InputStream?
        imageStream = this.contentResolver.openInputStream(imageUri)
        val selectedImage = BitmapFactory.decodeStream(imageStream)

        // Convert bitmap to Base64 encoded image for web
        val byteArrayOutputStream = ByteArrayOutputStream()
        selectedImage.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream)
        val byteArray = byteArrayOutputStream.toByteArray()

        val imageBase64 = Base64.encodeToString(byteArray, Base64.DEFAULT)
        logoImage = "data:image/png;base64,$imageBase64"
    } catch (e: FileNotFoundException) {
        println("Error: ${e.localizedMessage}, ${e.message}")
    }

    str = str.replace("#LOGO#", logoImage ?: "")