自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

JS圖片壓縮的實現(xiàn)思路

開發(fā) 前端
涉及到 JS 的圖片壓縮,我的想法是需要用到 Canvas 的繪圖能力,通過調(diào)整圖片的分辨率或者繪圖質(zhì)量來達到圖片壓縮的效果。

前言

說起圖片壓縮,大家想到的或者平時用到的很多工具都可以實現(xiàn),例如,客戶端類的有圖片壓縮工具 PPDuck3, JS 實現(xiàn)類的有插件 compression.js ,亦或是在線處理類的 OSS 上傳,文件上傳后,在訪問文件時中也有圖片的壓縮配置選項,不過,能不能自己擼一套  JS 實現(xiàn)的圖片壓縮代碼呢?當然可以,那我們先來理一下思路。

壓縮思路

涉及到 JS 的圖片壓縮,我的想法是需要用到 Canvas 的繪圖能力,通過調(diào)整圖片的分辨率或者繪圖質(zhì)量來達到圖片壓縮的效果,實現(xiàn)思路如下:

  •  獲取上傳 Input 中的圖片對象 File
  •  將圖片轉換成 base64 格式
  •  base64 編碼的圖片通過 Canvas 轉換壓縮,這里會用到的 Canvas 的 drawImage 以及 toDataURL 這兩個 Api,一個調(diào)節(jié)圖片的分辨率的,一個是調(diào)節(jié)圖片壓縮質(zhì)量并且輸出的,后續(xù)會有詳細介紹
  •  轉換后的圖片生成對應的新圖片,然后輸出

優(yōu)缺點介紹

不過 Canvas 壓縮的方式也有著自己的優(yōu)缺點:

  •  優(yōu)點:實現(xiàn)簡單,參數(shù)可以配置化,自定義圖片的尺寸,指定區(qū)域裁剪等等。
  •  缺點:只有 jpeg 、webp 支持原圖尺寸下圖片質(zhì)量的調(diào)整來達到壓縮圖片的效果,其他圖片格式,僅能通過調(diào)節(jié)尺寸來實現(xiàn)

代碼實現(xiàn) 

  1. <template>  
  2.   <div class="container">  
  3.     <input type="file" id="input-img" @change="compress" />  
  4.     <a :download="fileName" :href="compressImg" >普通下載</a>  
  5.     <button @click="downloadImg">兼容 IE 下載</button>  
  6.     <div>  
  7.       <img :src="compressImg" />  
  8.     </div>  
  9.   </div>  
  10. </template>  
  11. <script>  
  12. export default {  
  13.   name: 'compress',  
  14.   data: function() {  
  15.     return {  
  16.       compressImg: null,  
  17.       fileName: null,  
  18.     };  
  19.   },  
  20.   components: {},  
  21.   methods: {  
  22.     compress() {  
  23.       // 獲取文件對象  
  24.       const fileObj = document.querySelector('#input-img').files[0];  
  25.       // 獲取文件名稱,后續(xù)下載重命名  
  26.       this.fileName = `${new Date().getTime()}-${fileObj.name}`;  
  27.       // 獲取文件后綴名  
  28.       const fileNames = fileObj.name.split('.');  
  29.       const type = fileNames[fileNames.length-1];  
  30.       // 壓縮圖片  
  31.       this.handleCompressImage(fileObj, type);  
  32.     },  
  33.     handleCompressImage(img, type) {  
  34.       const vm = this 
  35.       let reader = new FileReader();  
  36.       // 讀取文件  
  37.       reader.readAsDataURL(img);  
  38.       reader.onload = function(e) {  
  39.         let image = new Image(); //新建一個img標簽  
  40.         image.src = e.target.result;  
  41.         image.onload = function() { 
  42.            let canvas = document.createElement('canvas');  
  43.           let context = canvas.getContext('2d');  
  44.           // 定義 canvas 大小,也就是壓縮后下載的圖片大小  
  45.           let imageimageWidth = image.width; //壓縮后圖片的大小  
  46.           let imageimageHeight = image.height;  
  47.           canvas.width = imageWidth 
  48.           canvas.height = imageHeight 
  49.            // 圖片不壓縮,全部加載展示  
  50.           context.drawImage(image, 0, 0);  
  51.           // 圖片按壓縮尺寸載入  
  52.           // let imageWidth = 500; //壓縮后圖片的大小  
  53.           // let imageHeight = 200 
  54.           // context.drawImage(image, 0, 0, 500, 200);  
  55.           // 圖片去截取指定位置載入  
  56.           // context.drawImage(image,100, 100, 100, 100, 0, 0, imageWidth, imageHeight);  
  57.           vm.compressImg = canvas.toDataURL(`image/${type}`);  
  58.         };  
  59.       };  
  60.     },  
  61.     // base64 圖片轉 blob 后下載  
  62.     downloadImg() {  
  63.       let parts = this.compressImg.split(';base64,');  
  64.       let contentType = parts[0].split(':')[1];  
  65.       let raw = window.atob(parts[1]);  
  66.       let rawrawLength = raw.length;  
  67.       let uInt8Array = new Uint8Array(rawLength);  
  68.       for(let i = 0; i < rawLength; ++i) {  
  69.         uInt8Array[i] = raw.charCodeAt(i);  
  70.       }  
  71.       const blob = new Blob([uInt8Array], {type: contentType});  
  72.       this.compressImg = URL.createObjectURL(blob);  
  73.       if (window.navigator.msSaveOrOpenBlob) {  
  74.         // 兼容 ie 的下載方式  
  75.         window.navigator.msSaveOrOpenBlob(blob, this.fileName);  
  76.       }else{  
  77.         const a = document.createElement('a');  
  78.         a.href = this.compressImg;  
  79.         a.setAttribute('download', this.fileName);  
  80.         a.click();  
  81.       }  
  82.     },  
  83.   }  
  84. };  
  85. </script> 

上面的代碼是可以直接拿來看效果的,不喜歡用 Vue 的也可以把代碼稍微調(diào)整一下,下面開始具體分解一下代碼的實現(xiàn)思路

Input 上傳 File 處理

將 File 對象通過 FileReader 的 readAsDataURL 方法轉換為URL格式的字符串(base64 編碼) 

  1. const fileObj = document.querySelector('#input-img').files[0];  
  2. let reader = new FileReader();  
  3. // 讀取文件  
  4. reader.readAsDataURL(fileObj); 

Canvas 處理 File 對象

建立一個 Image 對象,一個 canvas 畫布,設定自己想要下載的圖片尺寸,調(diào)用 drawImage 方法在 canvas 中繪制上傳的圖片 

  1. let image = new Image(); //新建一個img標簽  
  2. image.src = e.target.result;  
  3. let canvas = document.createElement('canvas');  
  4. let context = canvas.getContext('2d');  
  5. context.drawImage(image, 0, 0); 

Api 解析:drawImage 

  1. context.drawImage(img, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight); 

img

就是圖片對象,可以是頁面上獲取的 DOM 對象,也可以是虛擬 DOM 中的圖片對象。

dx、dy、dWidth、dHeight

表示在 canvas 畫布上規(guī)劃出一片區(qū)域用來放置圖片,dx, dy 為繪圖位置在 Canvas 元素的 X 軸、Y 軸坐標,dWidth, dHeight 指在 Canvas 元素上繪制圖像的寬度和高度(如果不說明, 在繪制時圖片的寬度和高度不會縮放)。

sx、sy、swidth、sheight

這 4 個參數(shù)是用來裁剪源圖片的,表示圖片在 canvas 畫布上顯示的大小和位置。sx, sy 表示在源圖片上裁剪位置的 X 軸、Y 軸坐標,然后以 swidth, sheight 尺寸來選擇一個區(qū)域范圍,裁剪出來的圖片作為最終在 Canvas 上顯示的圖片內(nèi)容( swidth, sheight 不說明的情況下,整個矩形(裁剪)從坐標的 sx 和 sy 開始,到圖片的右下角結束)。

以下為圖片繪制的實例: 

  1. context.drawImage(image, 0, 0, 100, 100);  
  2. context.drawImage(image, 300, 300, 200, 200);  
  3. context.drawImage(image, 0, 100, 150, 150, 300, 0, 150, 150); 

Api 中奇怪之處在于,sx、sy、swidth、sheight 為選填參數(shù),但位置在 dx、dy、dWidth、dHeight 之前。

Canvas 輸出圖片

調(diào)用 canvas 的 toDataURL 方法可以輸出 base64 格式的圖片。 

  1. canvas.toDataURL(`image/${type}`); 

Api 解析:toDataURL 

  1. canvas.toDataURL(type, encoderOptions); 

type 可選

圖片格式,默認為 image/png。

encoderOptions 可選

在指定圖片格式為 image/jpeg 或 image/webp 的情況下,可以從 0 到 1 的區(qū)間內(nèi)選擇圖片的質(zhì)量。如果超出取值范圍,將會使用默認值 0.92。其他參數(shù)會被忽略。

a 標簽的下載

調(diào)用 <a> 標簽的 download 屬性,即可完成圖片的下載。

Api 解析:download 

  1. // href 下載必填  
  2. <a download="filename" href="href"> 下載 </a> 

filename

選填,規(guī)定作為文件名來使用的文本。

href

文件的下載地址。

非主流瀏覽器下載處理

到此可以解決 Chroma 、 Firefox 和 Safari(自測支持) 瀏覽器的下載功能,因為 IE 等瀏覽器不支持 download 屬性,所以需要進行其他方式的下載,也就有了代碼中的后續(xù)內(nèi)容 

  1. // base64 圖片轉 blob 后下載  
  2. downloadImg() {  
  3.   let parts = this.compressImg.split(';base64,');  
  4.   let contentType = parts[0].split(':')[1];  
  5.   let raw = window.atob(parts[1]);  
  6.   let rawrawLength = raw.length;  
  7.   let uInt8Array = new Uint8Array(rawLength);  
  8.   for(let i = 0; i < rawLength; ++i) {  
  9.     uInt8Array[i] = raw.charCodeAt(i);  
  10.   }  
  11.   const blob = new Blob([uInt8Array], {type: contentType});  
  12.   this.compressImg = URL.createObjectURL(blob);  
  13.   if (window.navigator.msSaveOrOpenBlob) {  
  14.     // 兼容 ie 的下載方式  
  15.     window.navigator.msSaveOrOpenBlob(blob, this.fileName);  
  16.   }else{  
  17.     const a = document.createElement('a');  
  18.     a.href = this.compressImg;  
  19.     a.setAttribute('download', this.fileName);  
  20.     a.click();  
  21.   }  
  •  將之前 canvas 生成的 base64 數(shù)據(jù)拆分后,通過 atob 方法解碼
  •  將解碼后的數(shù)據(jù)轉換成 Uint8Array 格式的無符號整形數(shù)組
  •  轉換后的數(shù)組來生成一個 Blob 數(shù)據(jù)對象,通過 URL.createObjectURL(blob) 來生成一個臨時的 DOM 對象
  •  之后 IE 類瀏覽器可以調(diào)用 window.navigator.msSaveOrOpenBlob 方法來執(zhí)行下載,其他瀏覽器也可以繼續(xù)通過 <a> 標簽的 download 屬性來進行下載

Api 解析:atob

base-64 解碼使用方法是 atob()。 

  1. window.atob(encodedStr) 

encodedStr

必需,是一個通過 btoa() 方法編碼的字符串,btoa() 是 base64 編碼的使用方法。

Api 解析:Uint8Array 

  1. new Uint8Array(length) 

length

創(chuàng)建初始化為 0 的,包含 length 個元素的無符號整型數(shù)組。

Api 解析:Blob

Blob 對象表示一個不可變、原始數(shù)據(jù)的類文件對象。 

  1. // 構造函數(shù)允許通過其它對象創(chuàng)建 Blob 對象  
  2. new Blob([obj],{type:createType})  

obj

字符串內(nèi)容

createType

要構造的類型

兼容性 IE 10 以上

Api 解析:createObjectURL

靜態(tài)方法會創(chuàng)建一個 DOMString。 

  1. objectURL = URL.createObjectURL(object); 

object

用于創(chuàng)建 URL 的 File 對象、Blob 對象或者 MediaSource 對象。

Api 解析:window.navigator 

  1. // 官方已不建議使用的文件下載方式,僅針對 ie 且兼容性 10 以上  
  2. // msSaveBlob 僅提供下載  
  3. // msSaveOrOpenBlob 支持下載和打開  
  4. window.navigator.msSaveOrOpenBlob(blob, fileName); 

blob

要下載的 blob 對象

fileName

下載后命名的文件名稱。

總結

本文僅針對圖片壓縮介紹了一些思路,簡單的使用場景可能如下介紹,當然也會引申出來更多的使用場景,這些還有待大家一起挖掘。

  •  上傳存儲圖片如果需要對文件大小格式有要求的,可以統(tǒng)一壓縮處理圖片
  •  前臺頁面想要編輯圖片,可以在 Canvas 處理圖片的時候,加一些其他邏輯,例如添加文字,剪裁,拼圖等等操作

當然溫馨提示:因部分接口有 IE 兼容性問題,IE 瀏覽器方面,僅能支持 IE 10 以上版本進行下載。

 

 

責任編輯:龐桂玉 來源: 前端大全
相關推薦

2016-11-02 18:43:02

javascripthtml5vue.js

2020-10-20 11:12:11

Nodejs

2024-04-19 08:31:40

Android屬性讀取

2024-07-04 08:26:12

AndroidJPEG圖片

2022-04-04 16:53:56

Vue.js設計框架

2020-08-05 16:09:52

javascript壓縮圖片前端

2022-07-17 11:22:35

前端開發(fā)圖片裁切壓縮上傳

2018-10-29 09:24:41

Web圖片壓縮網(wǎng)頁加速

2023-01-15 20:28:32

前端圖片壓縮

2023-11-04 12:43:44

前端圖片參數(shù)

2022-08-08 08:29:55

圖片壓縮前端互聯(lián)網(wǎng)

2019-12-11 10:50:06

JS圖片前端

2022-08-05 19:27:22

通用API鴻蒙

2022-08-01 12:53:30

前端動畫

2015-09-02 11:22:36

JavaScript實現(xiàn)思路

2020-08-21 09:58:16

谷歌Android工具

2015-05-18 09:59:48

ZooKeeper分布式計算Hadoop

2021-01-04 08:09:58

Node.js磁盤接口

2020-09-16 14:01:10

Vue.js項目語言

2021-12-26 23:34:00

微服務Istio壓縮
點贊
收藏

51CTO技術棧公眾號