@laverdet/lokesh-colorthief
Version:
Get the dominant color or color palette from an image.
2 lines (1 loc) • 2.25 kB
JavaScript
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e(require("@laverdet/lokesh-quantize/dist/index.mjs")):"function"==typeof define&&define.amd?define(["@laverdet/lokesh-quantize/dist/index.mjs"],e):(t||self).ColorThief=e(t.quantize)}(this,function(t){function e(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var n=e(t),o=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)};o.prototype.getImageData=function(){return this.context.getImageData(0,0,this.width,this.height)};var a=function(){};return a.prototype.getColor=function(t,e){return void 0===e&&(e=10),this.getPalette(t,5,e)[0]},a.prototype.getPalette=function(t,e,i){var a=function(t){var e=t.colorCount,n=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===n||!Number.isInteger(n)||n<1)&&(n=10),{colorCount:e,quality:n}}({colorCount:e,quality:i}),r=new o(t),u=function(t,e,n){for(var o,i,a,r,u,s=t,l=[],h=0;h<e;h+=n)i=s[0+(o=4*h)],a=s[o+1],r=s[o+2],(void 0===(u=s[o+3])||u>=125)&&(i>250&&a>250&&r>250||l.push([i,a,r]));return l}(r.getImageData().data,r.width*r.height,a.quality),s=n.default(u,a.colorCount);return s?s.palette():null},a.prototype.getColorFromUrl=function(t,e,n){var o=this,i=document.createElement("img");i.addEventListener("load",function(){var a=o.getPalette(i,5,n);e(a[0],t)}),i.src=t},a.prototype.getImageData=function(t,e){var n=new XMLHttpRequest;n.open("GET",t,!0),n.responseType="arraybuffer",n.onload=function(){if(200==this.status){var t=new Uint8Array(this.response);i=t.length;for(var n=new Array(i),o=0;o<t.length;o++)n[o]=String.fromCharCode(t[o]);var a=n.join(""),r=window.btoa(a);e("data:image/png;base64,"+r)}},n.send()},a.prototype.getColorAsync=function(t,e,n){var o=this;this.getImageData(t,function(t){var i=document.createElement("img");i.addEventListener("load",function(){var t=o.getPalette(i,5,n);e(t[0],this)}),i.src=t})},a});