1.1.24 • Published 10 months ago

tinypng-lib v1.1.24

Weekly downloads
-
License
MIT
Repository
github
Last release
10 months ago

TinyPNG图片压缩工具使用

image-20241005120141325

介绍

  • 基于tinypng的图片压缩工具,支持图片压缩功能。
  • 使用客户端压缩图片,无需上传到服务器,直接在客户端进行压缩。
  • 支持WebWork
  • npm:tinypng-lib
  • 在线体验地址:https://tinypng.wcrane.cn/

使用方法

  • 安装
npm install tinypng-lib
  • 基本使用
<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压缩后的文件名文件名称
/**
 * 压缩图片参数
 */
interface CompressOptions {
    minimumQuality?: number; // 最小质量
    quality?: number; // 压缩质量 0 - 100
    fileName?: string; // 压缩后的文件名, 默认为file.name
}

返回值说明

/**
 * 压缩图片结果
 */
interface CompressResult {
    success: boolean, // 是否成功
    file: File, // 压缩后的文件
    originalSize: number, // 原始文件大小
    compressedSize: number, // 压缩后文件大小
    rate: number, // 压缩率(压缩为原来的%)
    output: ArrayBuffer, // 压缩后的 ArrayBuffer
    blob: Blob, // 压缩后的 Blob
    rateString: string, // 压缩率字符串

}

WebWorker中使用

基本使用

image-20241005120050296 1. webpack项目中安装worker-loader

npm install worker-loader
  1. webpack.config.js中配置
module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /\.worker\.js$/,
        use: { loader: 'worker-loader' },
      },
    ],
  },
};
  1. 定义imageWorker.worker.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 });
    }
};
  1. 在组件中使用
  • 监听webworker的消息
  • 使用 TinyPNG.getImage 处理文件信息
  • 发送图片信息给webworker进行压缩
  • 接收webworker返回的压缩结果
<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>
  1. 说明:对于jpeg、jpg的图片不支持使用WebWorker压缩需要使用TinyPNG.compressJpegImage 进行压缩
import TinyPNG from 'tinypng-lib';
TinyPNG.compressJpegImage(file, options)

CompressWorker 使用

  • 封装代码
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 实例
// 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模块
1.1.24

10 months ago

1.1.23

10 months ago

1.1.22

10 months ago

1.1.21

10 months ago

1.1.20

10 months ago

1.1.19

10 months ago

1.1.18

10 months ago

1.1.17

10 months ago

1.1.16

10 months ago

1.1.14

10 months ago

1.1.13

10 months ago

1.1.12

10 months ago

1.1.11

10 months ago

1.1.10

10 months ago

1.1.9

10 months ago

1.1.8

10 months ago

1.1.7

10 months ago

1.1.3

10 months ago

1.1.2

10 months ago

1.1.1

10 months ago

1.1.0

10 months ago

1.0.43

10 months ago

1.0.42

10 months ago

1.0.41

10 months ago

1.0.40

10 months ago

1.0.39

10 months ago

1.0.38

10 months ago

1.0.37

10 months ago

1.0.48

10 months ago

1.0.36

10 months ago

1.0.47

10 months ago

1.0.46

10 months ago

1.0.45

10 months ago

1.0.44

10 months ago

1.0.35

10 months ago

1.0.34

10 months ago

1.0.33

10 months ago

1.0.32

10 months ago

1.0.31

10 months ago

1.0.30

10 months ago

1.0.29

10 months ago

1.0.25

10 months ago

1.0.24

10 months ago

1.0.15

10 months ago

1.0.14

10 months ago

1.0.13

10 months ago

1.0.12

10 months ago

1.0.11

10 months ago

1.0.10

10 months ago

1.0.9

10 months ago

1.0.8

10 months ago

1.0.7

10 months ago

1.0.6

10 months ago

1.0.5

10 months ago

1.0.4

10 months ago

1.0.3

10 months ago

1.0.2

10 months ago

1.0.1

10 months ago

1.0.0

10 months ago

0.1.1

10 months ago

0.1.0

10 months ago