获取图片的base64编码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
<!DOCTYPE html> < html > < head > < meta charset = "gbk" > < title ></ title > </ head > < body > < input accept = "image/*" name = "upimage" id = "upload_file" type = "file" onchange = "gen_base64()" > < br /> < textarea id = "base64_output" name = "Word" style = " width:820px" ></ textarea > < br /> < img src = "" id = "myImg" /> < script type = "text/javascript" > function $_(id) { return document.getElementById(id); } function gen_base64() { var file = $_('upload_file').files[0]; r = new FileReader(); //本地预览 r.onload = function(){ $_('base64_output').value = r.result; $_('myImg').src= r.result; } r.readAsDataURL(file); //Base64 } </ script > </ body > </ html > |
案例2:js压缩图片
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
<html> <body> <script> function getUrl(fil) { var Cnv = document.getElementById( 'myCanvas' ); var Cntx = Cnv.getContext( '2d' ); //获取2d编辑容器 var imgss = new Image(); //创建一个图片 var agoimg=document.getElementById( "ago" ); for ( var intI = 0; intI < fil.length; intI++) { //图片回显 var tmpFile = fil[intI]; var reader = new FileReader(); reader.readAsDataURL(tmpFile); reader.onload = function (e) { url = e.target.result; imgss.src = url; agoimg.src=url; agoimg.onload = function () { //等比缩放 var m = imgss.height / imgss.width; Cnv.width = 300 ; //该值影响缩放后图片的大小 Cnv.height =300*m; //img放入画布中 Cntx.drawImage(agoimg, 0, 0,300,300*m); //把画布中的数据,写出到某img的src里 var Pic = document.getElementById( "myCanvas" ).toDataURL( "image/png" ); var imgs =document.getElementById( "press" ); imgs.src =Pic ; } } } } </script> <input type= "file" id= "fileId" name= "fileId" value= "上传图片" hidefocus= "true" onchange= "getUrl(this.files);" /> <br/> <canvas id= "myCanvas" style= "display: block" ></canvas> old img::<img src= "" alt= "" id= "ago" style= "width: 500px;" /> new img::<img src= "" alt= "" id= "press" /> </body> </html> |
效果图
以上就是js获取图片的base64编码并压缩的详细内容,更多关于js 图片base64编码的资料请关注服务器之家其它相关文章!
原文链接:https://www.cnblogs.com/xiaoliu66007/p/12708890.html