前端使用js压缩图片上传
生活随笔
收集整理的這篇文章主要介紹了
前端使用js压缩图片上传
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
后端要求前端上傳圖片時進行壓縮,本文記錄js和canvas來壓縮圖片,時間有點久,忘記原文的地址了
// 上傳圖片壓縮, 調用此方法返回的blob文件,在FormData.append的時候file字段必須傳第三參數為文件名字compressImg(file) {const _that = this;var fileSize = parseFloat(parseInt(file["size"]) / 1024 / 1024).toFixed(2);var read = new FileReader();read.readAsDataURL(file);return new Promise(function(resolve) {const type = file.type,fileName = file.name;read.onload = function(e) {const img = new Image();img.src = e.target.result;img.onload = function() {//默認按比例壓縮let w = this.width > 1440 ? 1400 : this.width,h =this.width > 1440? 1440 * (this.height / this.width): this.height;//生成canvasconst canvas = document.createElement("canvas");const ctx = canvas.getContext("2d");let base64;// 創建屬性節點canvas.setAttribute("width", w);canvas.setAttribute("height", h);ctx.drawImage(this, 0, 0, w, h);// 圖像質量if (fileSize < 1) {//如果圖片小于一兆 那么不執行壓縮操作base64 = canvas.toDataURL(type, 1);} else if (fileSize > 1 && fileSize < 2) {//如果圖片大于1M并且小于2M 那么壓縮0.5 | 0.8base64 = canvas.toDataURL(type, 0.8);} else {//如果圖片超過2m 那么壓縮0.2base64 = canvas.toDataURL("image/jpeg", 0.2);}// 可兼容ie轉bloblet f = _that.base64URLtoFile(base64, fileName);// 不兼容ie轉file// let file = _that.base64ToFile(base64, fileName);resolve(f);};};});},總結
以上是生活随笔為你收集整理的前端使用js压缩图片上传的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 微信小程序插件wxParse的使用
- 下一篇: Jquery 禁用浏览器的 后退和前进按