圖片上傳壓縮圖片大小

//html
<ul class="ul-upload">
    <li></li>
    <li></li>
</ul>
<form id="uploadForm" method="post" enctype="multipart/form-data">
    <input type="file" id="uploadFile" name="uploadFile">
</form>
//js
$(".ul-upload li").click(function() { $("#uploadFile").click(); }); $("#uploadFile").change(function() { var val = $(this).val(); if (val != null && val != '') { var temp = val.substring(val.indexOf(".") + 1); if (temp == 'png' || temp == 'jpg') { var fileObj = document.getElementById("uploadFile").files[0]; // js
        var form = new FormData(); // FormData 對象
 imgCallBack(fileObj,form) } else { alert("請選擇後綴爲png、jpg的圖片上傳!") } } }); function imgCallBack(fileObj,form) { if (fileObj.size / 1024 > 1025) { // 大於1M,進行壓縮上傳
 photoCompress(fileObj, { quality : 0.2 }, function(base64Codes) { var bl = convertBase64UrlToBlob(base64Codes); form.append("file", bl, "file_" + Date.parse(new Date()) + ".jpg"); // 文件對象
 $.ajax({ url :'', type : 'POST', data : form, async : false, cache : false, contentType : false, processData : false, success : function(data) { } }); }); } else { form.append("file", fileObj); // 文件對象
 $.ajax({ url :'', type : 'POST', data : form, async : false, cache : false, contentType : false, processData : false, success : function(data) { } }); } } function photoCompress(file, w, objDiv) { var ready = new FileReader(); ready.readAsDataURL(file); ready.onload = function() { var re = this.result; canvasDataURL(re, w, objDiv) } } function canvasDataURL(path, obj, callback) { var img = new Image(); img.src = path; img.onload = function() { var that = this; // 默認按比例壓縮
        var w = that.width, h = that.height, scale = w / h; w = obj.width || w; h = obj.height || (w / scale); var quality = 0.7; // 默認圖片質量爲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); } } function convertBase64UrlToBlob(urlData) { var arr = urlData.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new Blob([u8arr], { type : mime }); }
相關文章
相關標籤/搜索