npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

tinypng-lib

v1.1.24

Published

tinypng图片压缩库,基于tinypng-lib-wasm,开箱即用,压缩图片

Downloads

104

Readme

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模块