我爱模板网 > 建站教程 > CSS3+HTML5 >  利用canvas将图片转成base64格式的两种方法正文

利用canvas将图片转成base64格式的两种方法

    本文是我爱模板网亲自实践的两种利用HTML5 CANVAS将图片转成base64格式的方法:

    第一种方法,参数是一个img对象:
function getBase64Image(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
 
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, img.width, img.height);
    var ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase();
    var dataURL = canvas.toDataURL("image/"+ext);
    return dataURL;
}
     第二种方法,在转换的同时,对图片进行了压缩:
function convertImgToBase64(url, callback, outputFormat) {
    var canvas = document.createElement('CANVAS');
    var ctx = canvas.getContext('2d');
    var img = new Image;
    img.crossOrigin = 'Anonymous';
    img.onload = function () {
        var width = img.width;
        var height = img.height;
        // 按比例压缩4倍
        var rate = (width < height ? width / height : height / width) / 4;
        canvas.width = width * rate;
        canvas.height = height * rate;
        ctx.drawImage(img, 0, 0, width, height, 0, 0, width * rate, height * rate);
        var dataURL = canvas.toDataURL(outputFormat || 'image/png');
        callback.call(this, dataURL);
        canvas = null;
    };
    img.src = url;
}



部分素材资源来源网站,本站提供免费下载,如有侵权请联系站长马上删除!
上一篇:position定位和translate平移让块状容器水平和垂直都居中 下一篇:html5+离开APP事件和返回APP事件,HTML5+APP前后台切换事件
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
选择头像:
最新评论

猜你喜欢