How to display Base64 images in HTML?

2018-12-31 04:23发布

I'm having trouble displaying a Base64 image inline.

Can someone point me in the right direction?

<!DOCTYPE html>
<html>
  <head>
    <title>Display Image</title>
  </head>
  <body>
    <img style='display:block; width:100px;height:100px;' id='base64image'                 
       src='data:image/jpeg;base64, LzlqLzRBQ...<!-- base64 data -->' />
  </body>
</html>

10条回答
孤独总比滥情好
2楼-- · 2018-12-31 04:37

You need to specify correct Content-type, Content-encoding and charset like

 data:image/jpeg;charset=utf-8;base64, 

according to the syntax of the data URI scheme:

 data:[<media type>][;charset=<character set>][;base64],<data>

Also refer http://danielmclaren.com/node/90

查看更多
墨雨无痕
3楼-- · 2018-12-31 04:44

My suspect is of course actual base64 data, otherwise it looks good to me. See this fiddle where similar scheme is working. You may try specifying char set.

<div>
    <p>Taken from wikpedia</p>
    <img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
    9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />
</div> 

You can try this base64 decoder to see if your base64 data is correct or not.

查看更多
几人难应
4楼-- · 2018-12-31 04:52

The + character occurring in a data URI should be encoded as %2B. This is like encoding any other string in a URI. For example, argument separators (? and &) must be encoded when a URI with an argument is sent as part of another URI.

查看更多
孤独总比滥情好
5楼-- · 2018-12-31 04:52

you can put your data directly in a url statment like

src = 'url(imageData)' ;

and to get the image data u can use the php function

$imageContent = file_get_contents("imageDir/".$imgName);

$imageData = base64_encode($imageContent);

so you can copy paste the value of imageData and paste it directly to your url and assign it to the src attribute of your image

查看更多
像晚风撩人
6楼-- · 2018-12-31 04:52

Try this one too:

let base64="iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
let buffer=Uint8Array.from(atob(base64), c => c.charCodeAt(0));
let blob=new Blob([buffer], { type: "image/gif" });
let url=URL.createObjectURL(blob);
let img=document.createElement("img");
img.src=url;
document.body.appendChild(img);

Not recommended for production as it is only compatible with modern browsers.

查看更多
步步皆殇っ
7楼-- · 2018-12-31 04:53

This will show image of base 64 data:

<style>
.logo {
            width: 290px;
            height: 63px;
            background: url(data:image/png;base64,copy-paste-base64-data-here) no-repeat;
        }
</style>

<div class="logo"/>
查看更多
登录 后发表回答