@drgd/aura
Version:
Extract color palettes from any image. Works on both server and client.
2 lines • 1.79 kB
JavaScript
import{a as p,b as y,c as A,d as x,e as E,f as M}from"./chunk-VRJCZRLL.js";import B from"sharp";var T=400,k=1e3;async function q(o,a={}){let s=a.paletteSize??6;if(s<1||s>12)throw new Error("[@drgd/aura] - Number of colors must be between 1 and 12");if(typeof o=="string"&&a.validateUrl!==!1&&!o.startsWith("data:"))try{await E(o)}catch(r){throw r}try{let r,n=a.quality==="low"?200:a.quality==="medium"?400:a.quality==="high"?800:T;if(Buffer.isBuffer(o))r=o;else if(typeof o=="string"){let t=new AbortController,u=setTimeout(()=>t.abort(),a.timeout??1e4),e=await fetch(o,{signal:t.signal});if(clearTimeout(u),!e.ok)throw new Error(`[@drgd/aura] - Failed to fetch image: ${e.statusText}`);let i=await e.arrayBuffer();r=Buffer.from(i)}else throw new Error("[@drgd/aura] - Invalid input: Must be a URL string or a Buffer");let l=B(r),f=await l.metadata();if(!f.width||!f.height)throw new Error("[@drgd/aura] - Invalid image dimensions");let m=l.rotate().resize(n,n,{fit:"inside",withoutEnlargement:!0}).removeAlpha().raw().toBuffer({resolveWithObject:!0}),{data:c,info:w}=await m,d=new Map;for(let t=0;t<c.length;t+=3*k){let u=Math.min(t+3*k,c.length);for(let e=t;e<u;e+=3){let i=c[e],g=c[e+1],h=c[e+2];if(i+g+h<20||i+g+h>760)continue;let C=`${i},${g},${h}`,b=d.get(C);b?b.count++:d.set(C,new p(i,g,h))}}let v=Array.from(d.values()),I=w.width*w.height,S=Math.ceil(Math.sqrt(s)),z=x(v,S);return A(z,s).map(t=>({hex:y(t.r,t.g,t.b),weight:t.count/I})).sort((t,u)=>u.weight-t.weight)}catch(r){let n=a.fallbackColors??M;return console.error(`[@drgd/aura] - Failed to extract colors during processing: ${r instanceof Error?r.message:"Unknown error"}`),n.slice(0,s).map(l=>({...l,weight:l.weight/n.slice(0,s).reduce((f,m)=>f+m.weight,0)}))}}export{q as getAura};
//# sourceMappingURL=server.js.map