html5前端图片压缩,大小可配置

时间:2025-04-03 18:20:19
/***思路:创建一个HTML5 Canvas画布自定义大小,将图片传入,再获取画布内容。简单粗暴有效! ****/
     

 /**  2016年3月3日
         * 图片压缩,大仙造
         * 技术交流495120021
         * @param fil
         * @param id
         */
        function getUrl(fil, id) {
            var Cnv = ('myCanvas');
            var Cntx = ('2d');//获取2d编辑容器
            var imgss =   new Image();
            var agoimg=("ago");
            for (var intI = 0; intI < ; intI++) {
                var tmpFile = fil[intI];
                var reader = new FileReader();
                (tmpFile);
                 = function (e) {
                    url = ;
                     = url;
                    =url;
                     = function () {
                        //等比缩放
                        var m =  / ;
                          =300;//该值影响缩放后图片的大小
                         = 300*m ;
                        //img放入画布中
                        //设置起始坐标,结束坐标
                        (agoimg, 0, 0,300*m,300);
                    }
                }
            }
        }


        function  pressss(){//
            //获取canvas压缩后的图片数据
            var Pic = ("myCanvas").toDataURL("image/png");
            var imgs =("press");
             =Pic ;
            //上传
            // 去除多余,得到base64编码的图片字节流
            Pic = (/^data:image\/(png|jpg);base64,/, "");
            //可以用ajax提交到后台,提交后可以直接存数据库,也可以保存成图片,此处略。


        }

<input type="file"  name="fileId" value="上传图片"
       hidefocus="true" οnchange="getUrl(,);"/>
<canvas      style="display: none" ></canvas>
old img-><img src="" alt=""  style="width: 500px;"/>
<input type="button" value="ya suo->" οnclick="pressss()" />
new img-><img src="" alt="" />
</body>

</html>

直接复制粘贴上面html代码 或者通过下面链接下载

下载地址:demo下载