我如何将image src属性设置为base64字符串?

问题描述 投票:0回答:1

我有一个小的Web应用程序,它接收一个.png图像,并在对其进行修改后使用json将其发送回客户端。 json包含表示图像的base64字符串。每当我尝试将src属性设置为字符串时,图像都会损坏。如何成功设置图像?字符串看起来像这样:

“ data:image / png; base64,iFBORgwKGgoAAAAMSEhEUgEAAR8AAQEgCAYBAQFyenn0AQACJUhDQVNYhe3VT0 ...”

HTML:

<img id="img" src="" />

JS:

// this function sends the image to the server
this.awaitResponse(imgData)
.then(response => {

    // retrieve the base64 string
    let str = response['enc']

    // retrieve the image element
    let img = document.getElementById("img");

    // set src attribute to the string
    img.setAttribute("src", str);
});
javascript image base64 setattribute
1个回答
0
投票

您需要使用.src。示例:

// this function sends the image to the server
this.awaitResponse(imgData)
.then(response => {

    // retrieve the base64 string
    let str = response['enc']

    // retrieve the image element
    let img = document.getElementById("img");

    // set src attribute to the string
    img.src(str);
});
© www.soinside.com 2019 - 2024. All rights reserved.