一款强大的HTML5+jQuery图片上传压缩预览代码,上传图片并压缩显示。
js代码
<script> (function ($) { $.extend({ //压缩图片,参数1:file对象,参数2:压缩比例 compress(file,scale) { return new Promise(function (resolve,reject) { let _scale=scale || 1; let cvs = document.createElement(\'canvas\'); let ctx = cvs.getContext(\'2d\'); let img = new window.Image(); let imgType=file.type; img.src = URL.createObjectURL(file); img.onload=function () { cvs.width = img.width*_scale; cvs.height = img.height*_scale; ctx.drawImage(img, 0, 0, cvs.width, cvs.height); resolve(cvs.toDataURL(imgType)); } }); } }); $.fn.extend({ //复制节点 cloneNode(num){ let p=this.parent(); for (let i=0;i<num;i++){ p.append(this.clone(true)) } } }); $(function () { $(\'li\').cloneNode(6);//复制66个节点 //点击触发input $(\'li\').each(function (i) { $(this).click(function () { $(\'input\').attr(\"name\",\'input_\'+i).click(); }) }); $(\"input\").change(function () { let files=$(this)[0].files[0];//获取files对象 let index=parseInt(($(this).attr(\'name\')).split(\"_\")[1]); //0.5为当前压缩比 $.compress(files,0.5).then((url)=>{ $(\'li\').eq(index).css({\"background-image\": \"url(\"+url+\")\"}); //上传到服务器 $.post(\'url\',{base64:url},()=>{ }) }) }) }) })(jQuery) </script>
暂无评论内容