1.js
/*canvas壓縮圖片 *width:壓縮后寬度 *height:壓縮后高度 *img:img dom對象 */ function compressImg(width, height, img) { var canvas = document.createElement('canvas'), c = canvas.getContext('2d'); canvas.width = width; canvas.height = height; c.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight, 0, 0, width, height); return canvas.toDataURL('image/png'); }
2.按比例壓縮調用方式
var img = new Image(); img.src = reader.result; img.onload = function () { var w = this.width, h = this.height, scale = w / h; //壓縮圖片 var b64 = compressImg(600, 600 / scale, img); }