Blogger Information
Blog 39
fans 1
comment 0
visits 62355
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
上传压缩图片
Dai的博客
Original
1137 people have browsed it
/**
 * 图片压缩,默认同比例压缩
 * @param {Object} f
 *   图片文件
 * @param {Object} obj
 *   obj 对象 有 width, height, quality(0-1)
 * @param {Object} callback
 *   回调函数有一个参数,base64的字符串数据
 */
function coursePptChange(f,obj, callback){
    var MyTest = f.files[0];
    var reader = new FileReader();
    reader.readAsDataURL(MyTest);
    reader.onload = function(theFile) {
        var img = new Image();
        img.src = theFile.target.result;
        img.onload = function(){
            var that = this;
            console.log(that.length);
            // 默认按比例压缩
            var w = that.width,
                h = that.height,
                scale = w / h;
            w = obj.width || w;
            h = obj.height || (w / scale);
            var quality = 0.1;  // 默认图片质量为0.7
            //生成canvas
            var canvas = document.createElement('canvas');
            var ctx = canvas.getContext('2d');
            // 创建属性节点
            var anw = document.createAttribute("width");
            anw.nodeValue = w;
            var anh = document.createAttribute("height");
            anh.nodeValue = h;
            canvas.setAttributeNode(anw);
            canvas.setAttributeNode(anh);
            ctx.drawImage(that, 0, 0, w, h);
            // 图像质量
            if(obj.quality && obj.quality <= 1 && obj.quality > 0){
                quality = obj.quality;
            }
            // quality值越小,所绘制出的图像越模糊
            var base64 = canvas.toDataURL('image/jpeg', quality );
            // 回调函数返回base64的值
            callback(base64);
        }
    };
}
// 调用函数处理图片      
// coursePptChange(this, {
//     // 注意:在pc端可以用绝对路径或相对路径,移动端最好用绝对路径
//     width : 200
// }, function(base){
//     //直接将获取到的base64的字符串,放到一个image标签中就可看到测试后的压缩之后的样式图了
//     console.log(base.length);
//     document.getElementById("faceSrc").src = base;
//     console.log("压缩后:" + base.length / 1024 + " " + base);
// })


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post