介紹
- 基于
tinypng
的圖片壓縮工具,支持圖片壓縮功能。 - 使用客戶端壓縮圖片,無需上傳到服務器,直接在客戶端進行壓縮。
- 支持WebWork
- npm:tinypng-lib
- 在線體驗地址:tinypng.wcrane.cn/
使用方法
- 安裝
shell代碼解讀復制代碼npm install tinypng-lib
- 基本使用
html代碼解讀復制代碼<template> <div id="app"> <input type="file" @input="uploadImg" /> <img :src="imgUrl" alt=""> </div> </template> <script> import TinyPNG from 'tinypng-lib' export default { name: 'App', components: { }, data() { return { imgUrl: '' } }, methods: { async uploadImg(e) { const file = e.target.files[0]; try { const res = await TinyPNG.compress(file, {}) console.log('res', res) const url = URL.createObjectURL(res.blob) const img = new Image() this.imgUrl = url } catch (error) { console.log("error", error) } } } } </script>
參數說明
參數 | 說明 | 默認值 |
---|---|---|
minimumQuality | 最小質量 | 35 |
quality | 期望壓縮質量(0-100) | 88 |
fileName | 壓縮后的文件名 | 文件名稱 |
js代碼解讀復制代碼/** * 壓縮圖片參數 */ interface CompressOptions { minimumQuality?: number; // 最小質量 quality?: number; // 壓縮質量 0 - 100 fileName?: string; // 壓縮后的文件名, 默認為file.name }
返回值說明
js代碼解讀復制代碼/** * 壓縮圖片結果 */ interface CompressResult { success: boolean, // 是否成功 file: File, // 壓縮后的文件 originalSize: number, // 原始文件大小 compressedSize: number, // 壓縮后文件大小 rate: number, // 壓縮率(壓縮為原來的%) output: ArrayBuffer, // 壓縮后的 ArrayBuffer blob: Blob, // 壓縮后的 Blob rateString: string, // 壓縮率字符串 }
WebWorker中使用
基本使用
- webpack項目中安裝
worker-loader
shell代碼解讀復制代碼npm install worker-loader
- 在
webpack.config.js
中配置
js代碼解讀復制代碼module.exports = { // ... module: { rules: [ { test: /.worker.js$/, use: { loader: 'worker-loader' }, }, ], }, };
- 定義
imageWorker.worker.js
js代碼解讀復制代碼// imageWorker.worker.js import TinyPNG from 'tinypng-lib'; self.onmessage = async function (e) { const { image, options } = e.data; try { // 使用支持webWorker的方法 const result = await TinyPNG.compressWorkerImage(image, options); self.postMessage(result); } catch (error) { self.postMessage({ error: error.message }); } };
- 在組件中使用
- 監聽webworker的消息
- 使用
TinyPNG.getImage
處理文件信息 - 發送圖片信息給webworker進行壓縮
- 接收webworker返回的壓縮結果
js代碼解讀復制代碼<script> // Import the worker import ImageWorker from './imageWorker.worker.js'; // This is the bundled worker import { getSizeTrans } from '../utils'; import TinyPNG from 'tinypng-lib'; export default { name: 'Base', mounted() { // Start the worker when the component is mounted this.worker = new ImageWorker(); // Receive the message (compressed result) from the worker this.worker.onmessage = (e) => { this.compressing = false; const result = e.data; if (result.error) { console.error("Compression failed:", result.error); } else { // 拿到壓縮結果 console.log(e); } }; }, methods: { getSizeTrans, async uploadImg(e) { const file = e.file; // 獲取圖片信息 const image = await TinyPNG.getImage(file); // Send the file to the worker for compression this.worker.postMessage({ image, options: { minimumQuality: 30, quality: 85 } }); } }, beforeDestroy() { // Terminate the worker when the component is destroyed if (this.worker) { this.worker.terminate(); } } } </script>
- 說明:對于jpeg、jpg的圖片不支持使用WebWorker壓縮需要使用
TinyPNG.compressJpegImage
進行壓縮
js代碼解讀復制代碼import TinyPNG from 'tinypng-lib'; TinyPNG.compressJpegImage(file, options)
CompressWorker 使用
- 封裝代碼
js代碼解讀復制代碼import ImageWorker from './imageWorker.worker.js'; // 與前面imageWorker.worker.js一致 export class CompressWorker { worker = null; constructor() { this.worker = new ImageWorker(); } async compress(file, options) { // 獲取圖片信息 const image = await TinyPNG.getImage(file); return new Promise((resolve, reject) => { // 監聽worker的消息 this.worker.onmessage = (e) => { const result = e.data; if (result.error && !result.success) { console.error("Compression failed:", result.error); reject(result.error); } else { resolve(result); } }; // Send the file to the worker for compression this.worker.postMessage({ image, options }); }); } terminate() { if (this.worker) { this.worker.terminate(); this.worker = null; } } }
使用
- 實例化:
CompressWorker
只注冊一次就行,比如vue的mounted生命周期 - 圖片壓縮
- 頁面或者組件卸載的時候執行, 銷毀
CompressWorker
實例
- 實例化:
js代碼解讀復制代碼// 1. 只注冊一次就行,比如vue的mounted生命周期 compressWorker = new CompressWorker(); // 2. 監聽選擇的圖片,圖片壓縮 compressWorker.compress(file, { minimumQuality: 30, quality: 85 }).then((result) => { // 壓縮結果 console.log(result); }) // 3. 頁面或者組件卸載的時候執行, 銷毀webworker if (compressWorker) { compressWorker.terminate(); }
注意事項
- 請確保已經安裝了
tinypng-lib
模塊