1
/** * 压缩图片 * base64 : 图片base64字符串 * w : 图片宽高最大值 * callback : 回调函数 * quality : 压缩系数0-1之间, 默认0.92 * limit : 压缩限制字符串长度单位(KB) * 使用: * import { compressBase64 } from '@/utils' * compressBase64(原base64, 1000, async (base64) => { * console.log(base64.length) * }) */ export function compressBase64 (base64, w, callback, quality = 0.92, limit = 500) { let newImage = new Image() newImage.src = base64 newImage.setAttribute('crossOrigin', 'Anonymous') let imgWidth, imgHeight newImage.onload = function () { imgWidth = this.width imgHeight = this.height let canvas = document.createElement('canvas') let ctx = canvas.getContext('2d') if (Math.max(imgWidth, imgHeight) > w) { if (imgWidth > imgHeight) { canvas.width = w canvas.height = w * imgHeight / imgWidth } else { canvas.height = w canvas.width = w * imgWidth / imgHeight } } else { canvas.width = imgWidth canvas.height = imgHeight } ctx.clearRect(0, 0, canvas.width, canvas.height) ctx.drawImage(this, 0, 0, canvas.width, canvas.height) // 压缩语句 // let base64 = canvas.toDataURL('image/jpeg', quality) // 如想确保图片压缩到自己想要的尺寸,500字符长度以下,请加以下语句, quality初始值根据情况自定 let times = 0 while (base64.length / 1024 > limit) { // quality -= 0.01 base64 = canvas.toDataURL('image/jpeg', quality) // 限制3次,防止死循环 if (times >= 3) { console.log('compress times >= 3, break') break } times = times + 1 } // 回调函数返回,否则无法及时拿到该值 callback(base64) } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2019-02-16 POI 插入图片到Excel中