您的位置:首页技术文章
文章详情页

js获取图片的base64编码并压缩

浏览:27日期:2024-04-10 15:17:28

获取图片的base64编码

<!DOCTYPE html><html> <head> <meta charset='gbk'> <title></title> </head> <body> <input accept='image/*' name='upimage' type='file' onchange='gen_base64()'> <br/> <textarea name='Word' style=' width:820px'></textarea> <br/> <img src='https://www.haobala.com/bcjs/14276.html' /> <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压缩图片

<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' name='fileId' value='上传图片' hidefocus='true' onchange='getUrl(this.files);'/> <br/><canvas ></canvas>old img::<img src='https://www.haobala.com/bcjs/14276.html' alt='' />new img::<img src='https://www.haobala.com/bcjs/14276.html' alt='' /></body></html>

效果图

js获取图片的base64编码并压缩

以上就是js获取图片的base64编码并压缩的详细内容,更多关于js 图片base64编码的资料请关注好吧啦网其它相关文章!

标签: JavaScript
相关文章: