S realizes image compression, preview, and image Base64 conversion

//Encapsulate a function
function ImgToBase64(file, maxLen, callBack) {
var img = new Image();

var reader = new FileReader();//读取客户端上的文件
reader.onload = function () {
    var url = reader.result;//读取到的文件内容.这个属性只在读取操作完成之后才有效,并且数据的格式取决于读取操作是由哪个方法发起的.所以必须使用reader.onload,
    img.src = url;//reader读取的文件内容是base64,利用这个url就能实现上传前预览图片
};
img.onload = function () {
    //生成比例
    var width = img.width, height = img.height;
    //计算缩放比例
    var rate = 1;
    if (width >= height) {
        if (width > maxLen) {
            rate = maxLen / width;
        }
    } else {
        if (height > maxLen) {
            rate = maxLen / height;
        }
    };
    img.width = width * rate;
    img.height = height * rate;
    //生成canvas
    var canvas = document.createElement("canvas");
    var ctx = canvas.getContext("2d");
    canvas.width = img.width;
    canvas.height = img.height;
    ctx.drawImage(img, 0, 0, img.width, img.height);
    var base64 = canvas.toDataURL('image/jpeg', 0.9);
    callBack(base64);
};
reader.readAsDataURL(file);

}
//Call this function
$("#img").change(function () {
var file = $(this)[0].files[0];//Get the file selected by the input file control

        ImgToBase64(file, 720, function (base64) {
            $("#img1")[0].src = base64;//预览页面上预留一个img元素,载入base64
            $("#img1")[0].width = 300;//设定宽高,不然会自动按照压缩过的图片宽高设定,有可能超出预想的范围。

           //Upload base64 directly to the server using ajax, done
});
})
})

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324894479&siteId=291194637