失之毫厘,差之千里。——佚名

分享一个js图像库:

https://github.com/WangYuLue/image-conversion

image-20230607220756452

xmind

Install

1
2
3
4
5
npm i image-conversion --save

# or

yarn add image-conversion

Include the library

in browser:

1
<script src="https://cdn.jsdelivr.net/gh/WangYuLue/image-conversion/build/conversion.js"></script>

in CommonJS:

1
const imageConversion = require("image-conversion");

in ES6:

1
import * as imageConversion from 'image-conversion';

or

1
import {compress, compressAccurately} from 'image-conversion';

Use examples

1
<input id="demo" type="file" onchange="view()">
  1. Compress image to 200kb:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function view(){
const file = document.getElementById('demo').files[0];
console.log(file);
imageConversion.compressAccurately(file,200).then(res=>{
//The res in the promise is a compressed Blob type (which can be treated as a File type) file;
console.log(res);
})
}

// or use an async function
async function view() {
const file = document.getElementById('demo').files[0];
console.log(file);
const res = await imageConversion.compressAccurately(file,200)
console.log(res);
}
  1. Compress images at a quality of 0.9
1
2
3
4
5
6
7
function view(){
const file = document.getElementById('demo').files[0];
console.log(file);
imageConversion.compress(file,0.9).then(res=>{
console.log(res);
})
}