js(canvas) 图片压缩

复制代码
 1 function compress(url, width, height) {
 2     return new Promise((resolve, reject) => {
 3         let img = document.createElement('img')
 4         img.onload = () => {
 5             let w = width
 6             let h = img.naturalHeight * (width / img.naturalWidth) //等比缩放
 7             if (h < height) {
 8                 w = img.naturalWidth * (height / img.naturalHeight)
 9                 h = height
10             }
11             let c = document.createElement('canvas')
12             c.width = width
13             c.height = height
14             let ctx = c.getContext('2d')
15             ctx.drawImage(img, 0, 0, w, h)
16             resolve(c.toDataURL('image/png'))
17         }
18         img.onerror = reject
19         img.src = url
20     })
21 }
复制代码

 

posted @   87de海雷  阅读(21)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示