首页 > 建站教程 > 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;
}