1+ <!DOCTYPE html>
2+ < html lang ="en ">
3+ < head >
4+ < meta charset ="UTF-8 ">
5+ < meta name ="viewport " content ="width=device-width, initial-scale=1.0 ">
6+ < meta http-equiv ="X-UA-Compatible " content ="ie=edge ">
7+ < title > js 图片转base64方式</ title >
8+ </ head >
9+ < body >
10+ < p id ="container1 "> </ p >
11+ < script >
12+ getBase64 ( "./blurry_dog.png" )
13+ function getBase64 ( imgUrl ) {
14+ window . URL = window . URL || window . webkitURL ;
15+ var xhr = new XMLHttpRequest ( ) ;
16+ xhr . open ( "get" , imgUrl , true ) ;
17+ xhr . responseType = "blob" ;
18+ xhr . onload = function ( ) {
19+ if ( this . status == 200 ) {
20+ //得到一个blob对象
21+ var blob = this . response ;
22+ console . log ( "blob" , blob )
23+ // 至关重要
24+ var oFileReader = new FileReader ( ) ;
25+ oFileReader . onloadend = function ( e ) {
26+ var base64 = e . target . result ;
27+ console . log ( "方式一》》》》》》》》》" , base64 )
28+ } ;
29+ oFileReader . readAsDataURL ( blob ) ;
30+ //====为了在页面显示图片,可以删除====
31+ var img = document . createElement ( "img" ) ;
32+ img . onload = function ( e ) {
33+ window . URL . revokeObjectURL ( img . src ) ; // 清除释放
34+ } ;
35+ var src = window . URL . createObjectURL ( blob ) ;
36+ img . src = src
37+ document . getElementById ( "container1" ) . appendChild ( img ) ;
38+ //====为了在页面显示图片,可以删除====
39+
40+ }
41+ }
42+ xhr . send ( ) ;
43+ }
44+ </ script >
45+ </ body >
46+ </ html >
0 commit comments