分享一个前端等比压缩图片插件

no photo no bb。。。。程序猿的美感一般般,将就看看,主要是效果实现了就行了。

注意,当前的等比压缩精度可能不是很精确,最多有0.01的误差,就是说,js的parseInt结果不够准确,可能将宽度或高度多给了1像素。假如要求高的话可以自己再改改。



具体思路及兼容性:

兼容性别提了,这个用的是html5的canvas及文件api,ie6 7 8绝对没办法运行的。但是现代浏览器包括安卓ios都可以用----安卓该不会要支持到安卓2.0版本的浏览器吧?

思路:读取图片的原始尺寸,然后按照限制高度限制宽度获得最适合的尺寸,然后用canvas绘制这图片出来,就得到结果了。

下面是代码。

核心脚本:


/**
 * 这是基于html5的前端图片工具,压缩工具。
 */
var ImageResizer=function(opts){
    var settings={
        resizeMode:"auto"//压缩模式,总共有三种  auto,width,height auto表示自动根据最大的宽度及高度等比压缩,width表示只根据宽度来判断是否需要等比例压缩,height类似。
        ,dataSource:"" //数据源。数据源是指需要压缩的数据源,有三种类型,image图片元素,base64字符串,canvas对象,还有选择文件时候的file对象。。。
        ,dataSourceType:"image" //image  base64 canvas
        ,maxWidth:150 //允许的最大宽度
        ,maxHeight:200 //允许的最大高度。
        ,onTmpImgGenerate:function(img){} //当中间图片生成时候的执行方法。。这个时候请不要乱修改这图片,否则会打乱压缩后的结果。
        ,success:function(resizeImgBase64,canvas){

        }//压缩成功后图片的base64字符串数据。
        ,debug:false //是否开启调试模式。

    };
    var appData={};
    $.extend(settings,opts);

    var _debug=function(str,styles){
        if(settings.debug==true){
            if(styles){
                console.log(str,styles);
            }
            else{
                console.log(str);
            }
        }
    };
var innerTools={
        getBase4FromImgFile:function(file,callBack){

            var reader = new FileReader();
            reader.onload = function(e) {
                var base64Img= e.target.result;
                //var $img = $('<img>').attr("src", e.target.result)
                //$('#preview').empty().append($img)
                if(callBack){
                    callBack(base64Img);
                }
            };
            reader.readAsDataURL(file);
        }

    //--处理数据源。。。。将所有数据源都处理成为图片图片对象,方便处理。
        ,getImgFromDataSource:function(datasource,dataSourceType,callback){
            var _me=this;
            var img1=new Image();
            if(dataSourceType=="img"||dataSourceType=="image"){
            img1.src=$(datasource).attr("src");
            if(callback){
             callback(img1);
            }
            }
            else if(dataSourceType=="base64"){
                img1.src=datasource;
            if(callback){
             callback(img1);
            }            }
            else if(dataSourceType=="canvas"){
            img1.src = datasource.toDataURL("image/jpeg");
            if(callback){
             callback(img1);
            }
            }
            else if(dataSourceType=="file"){
                _me.getBase4FromImgFile(function(base64str){
                    img1.src=base64str;
                    if(callback){
                        callback(img1);
                    }
                });
            }

        }
       //计算图片的需要压缩的尺寸。当然,压缩模式,压缩限制直接从setting里面取出来。
    ,getResizeSizeFromImg:function(img){
       var _img_info={
                w:$(img)[0].naturalWidth,
                h:$(img)[0].naturalHeight
            };
        console.log("真实尺寸:");
        console.log(_img_info);
       var _resize_info={
           w:0
           ,h:0
       };
        if(_img_info.w<=settings.maxWidth&&_img_info.h<=settings.maxHeight){
            return _img_info;
        }
        if(settings.resizeMode=="auto"){
        var _percent_scale=parseFloat(_img_info.w/_img_info.h);
            var _size1={
                w:0
                ,h:0
            };
            var _size_by_mw={
                w:settings.maxWidth
                ,h:parseInt(settings.maxWidth/_percent_scale)
            };
            var _size_by_mh={
                w:parseInt(settings.maxHeight*_percent_scale)
                ,h:settings.maxHeight
            };
            if(_size_by_mw.h<=settings.maxHeight){
                return _size_by_mw;
            }
            if(_size_by_mh.w<=settings.maxWidth){
                return _size_by_mh;
            }

            return {
                w:settings.maxWidth
                ,h:settings.maxHeight
            };

        }
        if(settings.resizeMode=="width"){
            if(_img_info.w<=settings.maxWidth){
                return _img_info;
            }
            var _size_by_mw={
                w:settings.maxWidth
                ,h:parseInt(settings.maxWidth/_percent_scale)
            };
            return _size_by_mw;
        }

        if(settings.resizeMode=="height"){
            if(_img_info.h<=settings.maxHeight){

                return _img_info;
            }
            var _size_by_mh={
                w:parseInt(settings.maxHeight*_percent_scale)
                ,h:settings.maxHeight
            };
            return _size_by_mh;
        }

    }
    //--将相关图片对象画到canvas里面去。
    ,drawToCanvas:function(img,theW,theH,realW,realH,callback){

    var canvas = document.createElement("canvas");
        canvas.width=theW;
        canvas.height=theH;
        var ctx = canvas.getContext('2d');
        ctx.drawImage(img,
0,//sourceX,
0,//sourceY,
realW,//sourceWidth,
realH,//sourceHeight,
0,//destX,
0,//destY,
theW,//destWidth,
theH//destHeight
 );

        //--获取base64字符串及canvas对象传给success函数。
        var base64str=canvas.toDataURL("image/png");
        if(callback){
            callback(base64str,canvas);
        }
    }
    };

    //--开始处理。
    (function(){
        innerTools.getImgFromDataSource(settings.dataSource,settings.dataSourceType,function(_tmp_img){
            var __tmpImg=_tmp_img;
            settings.onTmpImgGenerate(_tmp_img);
            //--计算尺寸。
            var _limitSizeInfo=innerTools.getResizeSizeFromImg(__tmpImg);
            console.log(_limitSizeInfo);
            var _img_info={
                w:$(__tmpImg)[0].naturalWidth,
                h:$(__tmpImg)[0].naturalHeight
            };
            innerTools.drawToCanvas(__tmpImg,_limitSizeInfo.w,_limitSizeInfo.h,_img_info.w,_img_info.h,function(base64str,canvas){
              settings.success(base64str,canvas);
            });

        });
    })();

    var returnObject={


    };

    return returnObject;
};




html测试代码:


<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="/static/lib/jquery-1.11.0.min.js"></script>
    <script type="text/javascript" src="/static/lib/util.js"></script>
    <script type="text/javascript" src="ImageResizer.js"></script>
</head>
<body>
<h2>这是一个文件选择框,用于测试压缩工具和打水印。</h2>
<div>请选择图片以压缩图片。</div>
<div><input type="file" id="file"> </div>
<div>选择了这张图片。</div>
<div>
    <img id="preview"/>

</div>
<h3>压缩设置.</h3>
<div>

    <label>压缩模式:</label><select id="sel-mode">
        <option value="auto">自动</option>
        <option value="width">按照宽度压缩</option>
        <option value="height">按照高度压缩</option>
    </select>
    <label>压缩限制:</label>宽度:<input type="text" value="150" name="width" id="resize_width">x高度:<input type="text" value="200" name="height" id="resize_height">
    <input type="button" value="压缩" id="btn-resize" style="display: none;">

</div>
<div>这是压缩后的结果。</div>
<img id="result"/>

<script type="text/javascript">
    var _fileInput=document.getElementById("file");
    _fileInput.addEventListener("change",function(){

    if (_fileInput.files.length === 0) {
        alert("请选择图片");
        return; }
    var oFile = _fileInput.files[0];
    //if (!rFilter.test(oFile.type)) { alert("You must select a valid image file!"); return; }

    /*  if(oFile.size>5*1024*1024){
     message(myCache.par.lang,{cn:"照片上传:文件不能超过5MB!请使用容量更小的照片。",en:"证书上传:文件不能超过100K!"})
     changePanel("result");
     return;
     }*/
    if(!new RegExp("(jpg|jpeg|gif|png)+","gi").test(oFile.type)){
        alert("照片上传:文件类型必须是JPG、JPEG、PNG或GIF!");
        return;
    }

            var reader = new FileReader();
            reader.onload = function(e) {
                var base64Img= e.target.result;
                //var $img = $('<img>').attr("src", e.target.result)
                //$('#preview').empty().append($img)
                $("#preview").attr("src",base64Img);

                //--执行resize。
                var _ir=ImageResizer({
                        resizeMode:"auto"
                        ,dataSource:base64Img
                        ,dataSourceType:"base64"
                        ,maxWidth:parseInt($("#resize_width").val()) //允许的最大宽度
                        ,maxHeight:parseInt($("#resize_height").val()) //允许的最大高度。
                        ,onTmpImgGenerate:function(img){

                        }
                        ,success:function(resizeImgBase64,canvas){
                        $("#result").attr("src",resizeImgBase64);

                        }
                        ,debug:true
                });

            };
            reader.readAsDataURL(oFile);

    },false);
</script>
</body>
</html>


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 12
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值