canvas实现图片压缩
来源:互联网 发布:网络水军怎么看 编辑:程序博客网 时间:2024/06/04 17:43
使用H5canvas实现图片压缩
用于移动端图片上传,由于现在手机拍的照片动辄几M,如果直接上传速度慢也没有必要,这里利用H5 canvas实现图片压缩 基本原理是通过canvas渲染图片,再通过 toDataURL 方法压缩保存为base64字符串(能够编译为jpg格式的图片)
// 利用canvas压缩图片,传入四个参数,分别是data:获取到的文件,w, h 要压缩的宽高, 和一个回调函数将获取到的压缩文件传递出去 canvasCompressPic(data, w, h, callback) { let newImg = new Image(); newImg.src = data; let imgWidth, imgHeight; newImg.onload = () => { let img = document.createElement('img'); img.src = newImg.src; imgWidth = img.width; imgHeight = img.height; let canvas = document.createElement('canvas'); let ctx = canvas.getContext('2d'); if (imgWidth > imgHeight) { imgWidth = w * imgWidth / imgHeight; imgHeight = h; } else { imgHeight = h * imgHeight / imgWidth; imgWidth = w; }; canvas.width = imgWidth; canvas.height = imgHeight; ctx.clearRect(0, 0, w, h); // 处理png格式图片背景变黑的问题 ctx.fillStyle = '#fff'; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.drawImage(img, 0, 0, imgWidth, imgHeight); let rate = 0.7; let base64 = canvas.toDataURL('image/jpeg', rate); callback(base64); }; }
阅读全文
0 0
- canvas实现图片压缩
- 使用canvas实现图片压缩
- 使用canvas实现图片压缩
- HTML5 Canvas 实现本地压缩图片
- HTML5 Canvas 实现本地压缩图片
- html5+canvas实现图片的压缩上传
- H5 canvas实现客户端压缩图片上传
- 使用canvas实现图片压缩上传
- canvas实现图片压缩及复制
- 利用canvas实现前端压缩图片
- html canvas压缩图片
- 使用canvas压缩图片
- canvas压缩图片
- canvas图片体积压缩
- html5 canvas 图片压缩
- HTML5+Canvas实现本地压缩上传图片功能
- 利用canvas前端实现图片压缩后上传
- HTML5 canvas实现图片拉伸、压缩与裁剪
- 数据库_错题解析_11.6
- ubuntu下如何删除软件?
- filter 入门
- 69. Sqrt(x)
- BZOJ 1925 地精部落 DP
- canvas实现图片压缩
- 宜立方商城 工程搭建 项目(二)续
- try/catch/finally 顺序
- 2017.11.6与章丘四中互测章丘试题
- Verilog同步整形电路
- WEBGL学习【七】画布绘图
- Python高级编程-如何拆分含有多种分隔符的字符串?
- 如何优化sql语句
- [Lintcode] #116 跳跃游戏