mirror of
https://github.com/janishutz/color-thief.git
synced 2025-11-25 05:44:24 +00:00
2 lines
1.1 KiB
JavaScript
2 lines
1.1 KiB
JavaScript
import{getPixels as t}from"ndarray-pixels";import e from"@lokesh.dhakar/quantize";import o from"sharp";const r=(r,a=10,n=10)=>{const l=(t=>{let e=t.colorCount,o=t.quality;if(void 0!==e&&Number.isInteger(e)){if(1===e)throw new Error("colorCount should be between 2 and 20. To get one color, call getColor() instead of getPalette()");e=Math.max(e,2),e=Math.min(e,20)}else e=10;return(void 0===o||!Number.isInteger(o)||o<1)&&(o=10),{colorCount:e,quality:o}})({colorCount:a,quality:n});return new Promise((a,n)=>{(e=>new Promise((r,a)=>{o(e).toBuffer().then(t=>o(t).metadata().then(e=>({buffer:t,format:e.format}))).then(({buffer:e,format:o})=>t(e,o)).then(r).catch(a)}))(r).then(t=>{const o=t.shape[0]*t.shape[1],r=((t,e,o)=>{const r=[];for(let a=0;a<e;a+=o){const e=4*a,o=t[e+0],n=t[e+1],l=t[e+2],u=t[e+3];(void 0===u||u>=125)&&(o>250&&n>250&&l>250||r.push([o,n,l]))}return r})(Array.from(t.data),o,l.quality),n=e(r,l.colorCount),u=n?n.palette():null;a(u)}).catch(t=>{n(t)})})};module.exports={getColor:(t,e=10)=>new Promise((o,a)=>{r(t,5,e).then(t=>{o(t[0])}).catch(t=>{a(t)})}),getPalette:r};
|