JS实现下载图片,JS实现把图片转成Base64

//将远程图片转化为base64
function getBase64(img){
    function getBase64Image(img,width,height) {
        //width、height调用时传入具体像素值,控制大小 ,不传则默认图像大小
        var canvas = document.createElement("canvas");
        canvas.width = width ? width : img.width;
        canvas.height = height ? height : img.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        var dataURL = canvas.toDataURL();
        return dataURL;
    }
    var image = new Image();
    image.crossOrigin = '';
    image.src = img;
    return new Promise((resolve,reject)=>{
        image.onload =function (){
            resolve(getBase64Image(image));//将base64传给done上传处理
        }
    });
}
//把图片转换成base64
getBase64('http://json.la/vx.jpg').then(base64 => {
    console.log(base64)
}, err => {
    console.log(err)
})
//下载远程图片
function downloadFile(url) { 
    var aLink = document.createElement('a');
    var evt = document.createEvent("MouseEvents");
    evt.initEvent("click", false, false);
    aLink.download = url;
    aLink.href = url;
    aLink.dispatchEvent(evt);
}
downloadFile('http://json.la/vx.jpg')
赞(0) 打赏
取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

    暂无评论...