<input accept="image/gif,image/jpeg,image/jpg,image/png" type="file" id="up" />
$(function() { $("#up").change(function() { var file = this.files[0]; if(undefined == file){ return ; } r = new FileReader(); r.readAsDataURL(file); r.onload = function(e) { var base64 = e.target.result; } }); });
這樣就獲取到了圖片文件的base64編碼javascript
能夠把base64直接設置給img的src屬性,用作圖片回顯用html
var suofang = function(base64, bili, callback) { console.log("執行縮放程序,bili=" + bili); //處理縮放,轉格式 var _img = new Image(); _img.src = base64; _img.onload = function() { var _canvas = document.createElement("canvas"); var w = this.width / bili; var h = this.height / bili; _canvas.setAttribute("width", w); _canvas.setAttribute("height", h); _canvas.getContext("2d").drawImage(this, 0, 0, w, h); } }
壓縮圖片主要是經過長寬的縮放來縮小圖片java
var base64 = canvas.toDataURL("image/png");
_canvas.toBlob(function(blob) { console.log(blob.size); }, "image/jpeg");
function dataURItoBlob(base64Data) { var byteString; if(base64Data.split(',')[0].indexOf('base64') >= 0) byteString = atob(base64Data.split(',')[1]); else byteString = unescape(base64Data.split(',')[1]); var mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0]; var ia = new Uint8Array(byteString.length); for(var i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); } return new Blob([ia], { type: mimeString }); }
var fd = new FormData(); fd.append("file", blob); //fileData爲自定義 $.ajax({ type: "post", url: "/file/upload", async: true, data: fd, processData: false, contentType: false, success: function(r) { } });
<input accept="image/gif,image/jpeg,image/jpg,image/png" type="file" id="up" />
$(function() { $("#up").change(function() { imageDeal(this, dealChange); }); }) var dealChange = function(blob, base64) { var fd = new FormData(); fd.append("file", blob); //fileData爲自定義 $.ajax({ type: "post", url: "/file/upload", async: true, data: fd, processData: false, contentType: false, success: function(r) { } }); }
var imageDeal = function(ele, returnBase64) { //獲取file,轉成base64 var file = ele.files[0]; //取傳入的第一個文件 if(undefined == file) { //若是未找到文件,結束函數,跳出 return; } console.log("fileSize" + file.size); console.log(file.type); var r = new FileReader(); r.readAsDataURL(file); r.onload = function(e) { var base64 = e.target.result; var bili = 1.5; console.log("壓縮前:" + base64.length); suofang(base64, bili, returnBase64); } } var suofang = function(base64, bili, callback) { console.log("執行縮放程序,bili=" + bili); //處理縮放,轉格式 var _img = new Image(); _img.src = base64; _img.onload = function() { var _canvas = document.createElement("canvas"); var w = this.width / bili; var h = this.height / bili; _canvas.setAttribute("width", w); _canvas.setAttribute("height", h); _canvas.getContext("2d").drawImage(this, 0, 0, w, h); var base64 = _canvas.toDataURL("image/jpeg"); _canvas.toBlob(function(blob) { console.log(blob.size); if(blob.size > 1024*1024){ suofang(base64, bili, callback); }else{ callback(blob, base64); } }, "image/jpeg"); } }