UNPKG

@laverdet/lokesh-colorthief

Version:

Get the dominant color or color palette from an image.

2 lines (1 loc) 1.94 kB
import t from"@laverdet/lokesh-quantize/dist/index.mjs";const e=function(t){this.canvas=document.createElement("canvas"),this.context=this.canvas.getContext("2d"),this.width=this.canvas.width=t.naturalWidth,this.height=this.canvas.height=t.naturalHeight,this.context.drawImage(t,0,0,this.width,this.height)};e.prototype.getImageData=function(){return this.context.getImageData(0,0,this.width,this.height)};var n=function(){};n.prototype.getColor=function(t,e=10){return this.getPalette(t,5,e)[0]},n.prototype.getPalette=function(n,o,i){const a=function(t){let{colorCount:e,quality:n}=t;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===n||!Number.isInteger(n)||n<1)&&(n=10),{colorCount:e,quality:n}}({colorCount:o,quality:i}),r=new e(n),s=function(t,e,n){const o=t,i=[];for(let t,a,r,s,l,h=0;h<e;h+=n)t=4*h,a=o[t+0],r=o[t+1],s=o[t+2],l=o[t+3],(void 0===l||l>=125)&&(a>250&&r>250&&s>250||i.push([a,r,s]));return i}(r.getImageData().data,r.width*r.height,a.quality),l=t(s,a.colorCount);return l?l.palette():null},n.prototype.getColorFromUrl=function(t,e,n){const o=document.createElement("img");o.addEventListener("load",()=>{const i=this.getPalette(o,5,n);e(i[0],t)}),o.src=t},n.prototype.getImageData=function(t,e){let n=new XMLHttpRequest;n.open("GET",t,!0),n.responseType="arraybuffer",n.onload=function(){if(200==this.status){let t=new Uint8Array(this.response);i=t.length;let n=new Array(i);for(let e=0;e<t.length;e++)n[e]=String.fromCharCode(t[e]);let o=n.join(""),a=window.btoa(o);e("data:image/png;base64,"+a)}},n.send()},n.prototype.getColorAsync=function(t,e,n){const o=this;this.getImageData(t,function(t){const i=document.createElement("img");i.addEventListener("load",function(){const t=o.getPalette(i,5,n);e(t[0],this)}),i.src=t})};export{n as default};