class ImageMin { constructor (options) { this.file = options.file this.maxSize = options.maxSize || 1024 * 1024 this.quantity = parseFloat((this.file.size / this.maxSize).toFixed(2)) return new Promise((resolve, reject) => { if (this.quantity <= 1) { this.blobToDataURL(this.file).then(ev => { resolve({ base64: ev.target.result, res: this.file }) }) } else { this.mini(resolve, reject) } }) } mini (resolve, reject) { let { file, quantity } = this try { let reader = new FileReader() let img = new Image() reader.readAsDataURL(file) reader.onload = function (e) { img.src = e.target.result } img.onload = () => { // 缩放图片需要的canvas let canvas = document.createElement('canvas') let context = canvas.getContext('2d') // 图片原始尺寸 let originWidth = img.width let originHeight = img.height canvas.width = originWidth canvas.height = originHeight // 清除画布 context.clearRect(0, 0, originWidth, originHeight) // 图片压缩 context.drawImage(img, 0, 0, originWidth, originHeight) let newRes = canvas.toDataURL('image/jpeg', quantity) // base64 格式 let blob = this.dataURLtoBlob(newRes) if (blob.size > this.maxSize) { context.clearRect(0, 0, originWidth, originHeight) let scale = Math.sqrt(quantity) let targetWidth = parseInt(originWidth * scale) let targetHeight = parseInt(originHeight * scale) canvas.width = targetWidth canvas.height = targetHeight context.drawImage(img, 0, 0, originWidth, originHeight, 0, 0, targetWidth, targetHeight) newRes = canvas.toDataURL('image/jpeg') blob = this.dataURLtoBlob(newRes) } resolve({ base64: newRes, res: blob }) } } catch (e) { reject(e) } } blobToDataURL (blob) { return new Promise((resolve, reject) => { var fr = new FileReader() fr.onload = resolve fr.readAsDataURL(blob) }) } dataURLtoBlob (dataurl) { let arr = dataurl.split(',') let mime = arr[0].match(/:(.*?);/)[1] let bstr = atob(arr[1]) let n = bstr.length let u8arr = new Uint8Array(n) while (n--) { u8arr[n] = bstr.charCodeAt(n) } return new Blob([u8arr], { type: mime }) } } export default ImageMin