Async Node color quantization by native addon
Cquant is node-addon-api based node extension, with the performance of C++, you can easily compute the major color of an image. The core algorithm of Cquant is based on leptonica.
Electron Prebuild Supported Versions: v3 and v4.0.4
npm i cquant sharp
// install cquant and sharpAsync!
This package is async. You can run multiple task without blocking the main loop.
Basic
``` js
const cquant = require(‘cquant’)
// use sharp to convert image to RGB Buffer Array
const sharp = require(‘sharp’)
sharp(‘path/to/image’)
.raw() // convert raw buffer like [RGB RGB RGB RGB]
.toBuffer((_err, buffer, info) => {
if (!_err) {
let colorCount = 4
cquant.paletteAsync(buffer, info.channels, colorCount).then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
}
})
```
``` ts
/**
1000x1000
## Perf
> test result will be diff based on your local machine
### JPG 5572 x 3715 (No SubSample)
| Program | Time(ms) |
|---------------|:--------:|
| cquant | 60 ms |
| image-palette | N/A |
> N/A: crashed
### JPG 1920 x 1280 (No SubSample)
| Program | Time(ms) |
|---------------|:--------:|
| cquant | 12ms |
| image-palette | 950ms |
## Extra
### With `async.queue`
> If you have lots of image to process, the best way to do it is using [async](https://www.npmjs.com/package/async).queue for parallel, and controllable
``` js
// test/example.js
const myQueue = async.queue(async (filePath) => {
const img = await sharp(filePath)
.raw() // to raw
.toBuffer({ resolveWithObject: true })
const palette = await cquant.paletteAsync(img.data, img.info.channels, 5)
console.log(palette)
}, os.cpus().length - 1)
After running the install command make sure to use electron-rebuild to rebuild it for electron, usually it will just download the prebuild.
To be able to build from the source, you also need the standard build tool based on your OS.
npm run build
xVan Turing 2019