Why my Base64 encoded image could not show properly in img tag?

61 views Asked by At

I'm trying to use base64 to show an image, BUT it only shows the encoded string but not the image.

I copied it to a new file, and it showed correctly.

This is the code:

@customElement('image-board')
export class ImageBoard extends LitElement {
    // ...

    @property()
    imgSrc = ""

    render() {
        var img = ""
        if (this.imgSrc != "") {
            img = `<div> <img src="data:image/png;base64,${this.imgSrc}" /> </div>`;
        }

        return html`
            <div id="image-setter">
                ${img}
                <input type="file" id="imageInput" accept="image/png, image/jpeg" />
                <button @click=${this.setImage}>Set Image</button>
            </div>
        `
    }

    // ...
}

I use lit to build my components.

I'm sure that my imgSrc could either be an empty string or a valid base64 encoding image.

I've tried a smaller image (150 x 100 px) but it still could not run correctly.

incorrect output

However, the following is exactly what I want.

enter image description here

But I implement it by adding another img tag out of the component like:

<img id="outside-image"></img>
<image-board></image-board>

and set it's src by

let node = document.getElementById("outside-image");
node.src = `data:image/png;base64,${this.imgSrc}`

I'm confused that why it can not display correctly just by:

img = `<div> <img src="data:image/png;base64,${this.imgSrc}" /> </div>`;

PS: I'm not an English-speaker, so some expressions may not be accurate.

1

There are 1 answers

0
W.K.C On

If you wish to render the img HTML string, you need to pass it to the html template literal again. For example...

import {html, css, LitElement} from 'lit';
import {customElement, property} from 'lit/decorators.js';

@customElement('simple-greeting')
export class SimpleGreeting extends LitElement {
  render() {
    const base64 = '<some base64 image string>';

    // !!! pass the HTML string to `html` template literal again
    const img = html`
      <img src="${base64}" />
    `;
    
    return html`
      <div>${img}</div>
    `;
  }
}

See this lit playground demo in action