JS 前端 将图片转换为Base64利用H5 FileReader新特性

 
file = document.getElementById("image");
var file=file.files[0];
var fileName=file.name;

if(file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
alert('当前仅支持图片!');
return;
}
var size = Math.round(file.size / 1024 / 1024);
if (size > 2)
{
alert('图片大小不得超过2M');
return;
}

var reader = new FileReader();
imgUrlBase64 =reader.readAsDataURL(file);
reader.onload = function(e)
{
   reader.result;//读取到的base64文件流
  //此方法为异步方法,将调用的AJAX处理放在这个funtion里面
   ajax{
         //代码
         }
});
}.bind(this);
 
 
获取页面img 非上传
js = '''
let imgUrl=document.getElementById("captchaimg").src
var retURL="";
getBase64(imgUrl, dataURL => {
retURL=dataURL;
});
return retURL;
function getBase64(url, callback) {
var Img = new Image(),
dataURL = '';
Img.src = url + '?v=' + Math.random();
Img.setAttribute('crossOrigin', 'Anonymous');
Img.onload = function() {
var canvas = document.createElement('canvas'),
width = Img.width,
height = Img.height;
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(Img, 0, 0, width, height);
dataURL = canvas.toDataURL('image/jpeg');
return callback ? callback(dataURL) : null;
};
}
 
 
 
 

let c = document.createElement('canvas');let ctx = c.getContext('2d');
let img = document.getElementById("captchaimg"); console.log(img)
c.height=img.naturalHeight;c.width=img.naturalWidth;
ctx.drawImage(img, 0, 0,img.naturalWidth, img.naturalHeight)
let base64String = c.toDataURL();console.log(base64String)

selenium下载或保存图片最好的方法 |五十风的个人博客 (ikaze.cn)

 
 

posted on 2018-10-24 11:42  Ssumer  阅读(2012)  评论(0编辑  收藏  举报

导航