image-compressor: 前端图片压缩库

2025年10月20日 13:42:20
20370
file-upload image-compression image-compressor javascript 图片压缩
compressorjs fengyuanchen/compressorjs

超轻量的前端图片压缩库,就像一个智能“图片瘦身教练”,能在浏览器里直接把大图片压缩到合适大小,而且不影响视觉效果。 • 压缩后仅20KB,比一张表情包还小 • 支持JPEG、PNG、WebP等主流格式 • 零依赖,原生JavaScript编写 • 每周下载量稳定在10万+

项目大小 822 Byte
涉及语言 JavaScript 99.82% Shell 0.18%
许可协议 LICENSE
仓库同步说明
  • • 同步需要仓库写入权限以创建目标仓库
  • • 使用平台账号授权登录后将同步到您平台下的个人仓库

Compressor.js

Coverage Status Downloads Version Gzip Size

JavaScript image compressor. Uses the Browser’s native HTMLCanvasElement.toBlob() method to do the compression work, which means it is lossy compression, asynchronous, and has different compression effects in different browsers. Generally use this to precompress a image on the client side before uploading it.

Table of contents

Main Files

1
2
3
4
5
dist/
├── compressor.js        (UMD)
├── compressor.min.js    (UMD, compressed)
├── compressor.common.js (CommonJS, default)
└── compressor.esm.js    (ES Module)

Getting started

Install

1
npm install compressorjs

Usage

Syntax

1
new Compressor(file[, options])

file

The target image file for compressing.

options

  • Type: Object
  • Optional

The options for compressing. Check out the available options.

Example

1
<input type="file">
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import axios from 'axios';
import Compressor from 'compressorjs';
 
document.getElementById('file').addEventListener('change', (e) => {
  const file = e.target.files[0];
 
  if (!file) {
    return;
  }
 
  new Compressor(file, {
    quality: 0.6,
 
    // The compression process is asynchronous,
    // which means you have to access the `result` in the `success` hook function.
    success(result) {
      const formData = new FormData();
 
      // The third parameter is required for server
      formData.append('file', result, result.name);
 
      // Send the compressed image file to server with XMLHttpRequest.
      axios.post('/path/to/upload', formData).then(() => {
        console.log('Upload success');
      });
    },
    error(err) {
      console.log(err.message);
    },
  });
 
});

⬆ back to top

Options

You may set compressor options with new Compressor(file, options).
If you want to change the global default options, You may use Compressor.setDefaults(options).

strict

  • Type: boolean
  • Default: true

Indicates whether to output the original image instead of the compressed one when the size of the compressed image is greater than the original one’s, except the following cases:

  • The retainExif option is set to true.
  • The mimeType option is set and its value is different from the mime type of the image.
  • The width option is set and its value is greater than the natural width of the image.
  • The height option is set and its value is greater than the natural height of the image.
  • The minWidth option is set and its value is greater than the natural width of the image.
  • The minHeight option is set and its value is greater than the natural height of the image.
  • The maxWidth option is set and its value is less than the natural width of the image.
  • The maxHeight option is set and its value is less than the natural height of the image.

checkOrientation

  • Type: boolean
  • Default: true

Indicates whether to read the image’s Exif Orientation value (JPEG image only), and then rotate or flip the image automatically with the value.

Notes:

  • Don’t trust this all the time as some JPEG images have incorrect (not standard) Orientation values.
  • If the size of the target image is too large (e.g., greater than 10 MB), you should disable this option to avoid an out-of-memory crash.
  • The image’s Exif information will be removed after compressed, so if you need the Exif information, you may need to upload the original image as well.

retainExif

  • Type: boolean
  • Default: false

Indicates whether to retain the image’s Exif information after compressed.

maxWidth

  • Type: number
  • Default: Infinity

The max-width of the output image. The value should be greater than 0.

Avoid getting a blank output image, you might need to set the maxWidth and maxHeight options to limited numbers, because of the size limits of a canvas element, recommend to use 4096 or lesser.

maxHeight

  • Type: number
  • Default: Infinity

The max height of the output image. The value should be greater than 0.

minWidth

  • Type: number
  • Default: 0

The min-width of the output image. The value should be greater than 0 and should not be greater than the maxWidth.

minHeight

  • Type: number
  • Default: 0

The min-height of the output image. The value should be greater than 0 and should not be greater than the maxHeight.

width

  • Type: number
  • Default: undefined

The width of the output image. If not specified, the natural width of the original image will be used, or if the height option is set, the width will be computed automatically by the natural aspect ratio.

height

  • Type: number
  • Default: undefined

The height of the output image. If not specified, the natural height of the original image will be used, or if the width option is set, the height will be computed automatically by the natural aspect ratio.

resize

  • Type: string
  • Default: "none"
  • Options: "none", "contain", and "cover".

Sets how the size of the image should be resized to the container specified by the width and height options.

Note: This option only available when both the width and height options are specified.

quality

  • Type: number
  • Default: 0.8

The quality of the output image. It must be a number between 0 and 1. If this argument is anything else, the default values 0.92 and 0.80 are used for image/jpeg and image/webp respectively. Other arguments are ignored. Be careful to use 1 as it may make the size of the output image become larger.

Note: This option only available for image/jpeg and image/webp images.

Check out the documentation of the HTMLCanvasElement.toBlob() method for more detail.

Examples:

Quality Input size Output size Compression ratio Description
0 2.12 MB 114.61 KB 94.72% -
0.2 2.12 MB 349.57 KB 83.90% -
0.4 2.12 MB 517.10 KB 76.18% -
0.6 2.12 MB 694.99 KB 67.99% Recommend
0.8 2.12 MB 1.14 MB 46.41% Recommend
1 2.12 MB 2.12 MB 0% Not recommend
NaN 2.12 MB 2.01 MB 5.02% -

mimeType

  • Type: string
  • Default: 'auto'
  • Options: "auto", "image/png", "image/jpeg", and "image/webp".

The mime type of the output image. By default, the original mime type of the source image file will be used.

Note: Safari does not support mimeType conversion to "image/webp". For more details, see the browser compatibility of the HTMLCanvasElement.toBlob() method.

convertTypes

  • Type: Array or string (multiple types should be separated by commas)
  • Default: ["image/png"]
  • Examples:
    • ["image/png", "image/webp"]
    • "image/png,image/webp"

Files whose file type is included in this list, and whose file size exceeds the convertSize value will be converted to JPEGs.

For image file type support, see the Image file type and format guide.

convertSize

  • Type: number
  • Default: 5000000 (5 MB)

Files whose file type is included in the convertTypes list, and whose file size exceeds this value will be converted to JPEGs. To disable this, just set the value to Infinity.

Examples:

convertSize Input size (type) Output size (type) Compression ratio
5 MB 1.87 MB (PNG) 1.87 MB (PNG) 0%
5 MB 5.66 MB (PNG) 450.24 KB (JPEG) 92.23%
5 MB 9.74 MB (PNG) 883.89 KB (JPEG) 91.14%

beforeDraw(context, canvas)

  • Type: Function
  • Default: null
  • Parameters:
    • context: The 2d rendering context of the canvas.
    • canvas: The canvas for compression.

The hook function to execute before drawing the image into the canvas for compression.

1
2
3
4
5
6
7
new Compressor(file, {
  beforeDraw(context, canvas) {
    context.fillStyle = '#fff';
    context.fillRect(0, 0, canvas.width, canvas.height);
    context.filter = 'grayscale(100%)';
  },
});

drew(context, canvas)

  • Type: Function
  • Default: null
  • Parameters:
    • context: The 2d rendering context of the canvas.
    • canvas: The canvas for compression.

The hook function to execute after drawing the image into the canvas for compression.

1
2
3
4
5
6
7
new Compressor(file, {
  drew(context, canvas) {
    context.fillStyle = '#fff';
    context.font = '2rem serif';
    context.fillText('watermark', 20, canvas.height - 20);
  },
});

success(result)

  • Type: Function
  • Default: null
  • Parameters:
    • result: The compressed image (a File (read only) or Blob object).

The hook function to execute when successful to compress the image.

error(err)

  • Type: Function
  • Default: null
  • Parameters:
    • err: The compression error (an Error object).

The hook function executes when fails to compress the image.

⬆ back to top

Methods

abort()

Abort the compression process.

1
2
3
4
const compressor = new Compressor(file);
 
// Do something...
compressor.abort();

No conflict

If you have to use another compressor with the same namespace, just call the Compressor.noConflict static method to revert to it.

1
2
3
4
5
6
<script src="other-compressor.js">script>
<script src="compressor.js">script>
<script>
  Compressor.noConflict();
  // Code that uses other `Compressor` can follow here.
script>

Browser support

  • Chrome (latest)
  • Firefox (latest)
  • Safari (latest)
  • Opera (latest)
  • Edge (latest)
  • Internet Explorer 10+

Contributing

Please read through our contributing guidelines.

Versioning

Maintained under the Semantic Versioning guidelines.

License

MIT © Chen Fengyuan

⬆ back to top


                

                

免责声明 © 2026 - 虚宝阁

本站部分源码来源于网络,版权归属原开发者,用户仅获得使用权。依据《计算机软件保护条例》第十六条,禁止:

  • 逆向工程破解技术保护措施
  • 未经许可的分发行为
  • 去除源码中的原始版权标识

※ 本站源码仅用于学习和研究,禁止用于商业用途。如有侵权, 请及时联系我们进行处理。

侵权举报请提供: 侵权页面URL | 权属证明模板

响应时效:收到完整材料后48小时内处理

相关推荐

n8n: AI自动化工作流工具

n8n: AI自动化工作流工具

基于节点的自动化工作流工具,能帮助用户轻松创建和管理复杂的自动化流程,无需编写大量代码。并且内置了AI能力,支持 400+ 应用和服务!

146989 2025-09-26
jdenticon 独特几何头像生成器

jdenticon 独特几何头像生成器

一个用于生成独特且容易识别图像(identicons)的 JavaScript 库,可根据任意字符串(用户名、哈希值等)生成独特的几何图形,支持输出为 SVG 和 PNG 格式。

1591 2025-09-13
squish: 基于浏览器的图像压缩工具

squish: 基于浏览器的图像压缩工具

一个现代、基于浏览器的图像压缩工具,结合了现代Web技术和WebAssembly的性能优势,为开发者提供了便捷的图像优化解决方案。无论是处理个人照片还是批量优化网站资源,Squish都能满足多样化的需求。

1021 2025-10-05
adm-zip: nodejs 中 zip文件压缩神器

adm-zip: nodejs 中 zip文件压缩神器

ADM - ZIP是用于NodeJS的纯JavaScript实现的ZIP数据压缩库。可通过npm安装,无其他NodeJS依赖。能解压、压缩文件,更新ZIP内容。更多详情查看wiki。

2138 2025-08-28
ImageMagick: 图片处理瑞士军刀

ImageMagick: 图片处理瑞士军刀

ImageMagick是开源的命令行图片工具,压缩图片、转格式、加水印、切图都能一行命令搞定,还能批量处理如把100张图片批量压缩成WebP格式,自媒体、开发者都能用。

14651 2025-09-16
Seelen-UI: 高度可定制的 Windows 桌面美化工具

Seelen-UI: 高度可定制的 Windows 桌面美化工具

一款免费开源的 Windows 桌面增强工具,专注于高度自定义和效率提升。它采用 Rust 语言开发,结合 Tauri 框架与 Web 技术,支持窗口平铺管理、应用启动器、Dock、任务栏、动态壁纸、插件扩展等功能。

13691 2025-10-04

仓库下载

gitee

GitHub 下载代理

文件信息

文件名
文件大小
文件类型
代理耗时