Mickael Belhassen
Mickael Belhassen

Reputation: 47

Android: Display image from storage in webView using HTML

I have a webview that displays html, and I have a URI image that does not want to be displayed here is my code:

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

Here is my code:

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

The picture is not displayed

Upvotes: 3

Views: 135

Answers (1)

user9172697
user9172697

Reputation:

you have to convert an image to a bitmap, and then you will be able to display the bitmap in 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 ?: "")

Upvotes: 2

Related Questions