UNPKG

autohue.js

Version:

一个自动提取图片主题色让图片和背景融为一体的工具

8 lines 1.48 kB
/** * @name: autohue.js * @author: Larry Zhu * @version: 1.0.3 * @description: 一个自动提取图片主题色让图片和背景融为一体的工具 * @license: MIT */ !function(){"use strict";function t(t,n,u){let o=t/255,a=n/255,e=u/255;o=o>.04045?Math.pow((o+.055)/1.055,2.4):o/12.92,a=a>.04045?Math.pow((a+.055)/1.055,2.4):a/12.92,e=e>.04045?Math.pow((e+.055)/1.055,2.4):e/12.92;let s=.4124*o+.3576*a+.1805*e,c=.2126*o+.7152*a+.0722*e,r=.0193*o+.1192*a+.9505*e;s/=.95047,c/=1,r/=1.08883;const b=t=>t>.008856?Math.pow(t,.3333333333333333):7.787*t+.13793103448275862,g=b(s),i=b(c);return[116*i-16,500*(g-i),200*(i-b(r))]}function n(t,n){const u=t[0]-n[0],o=t[1]-n[1],a=t[2]-n[2];return Math.sqrt(u*u+o*o+a*a)}function u(t){return"#"+t.map((t=>{const n=Math.round(t).toString(16);return 1===n.length?"0"+n:n})).join("")}function o(u,o,a=10){const e=[],s=u.data,c=u.width,r=u.height;for(let u=0;u<r;u++)for(let r=0;r<c;r++){if(!o(r,u))continue;const b=4*(u*c+r);if(0===s[b+3])continue;const g=s[b],i=s[b+1],m=s[b+2],f=t(g,i,m);let h=!1;for(const t of e){if(n(f,t.averageLab)<a){t.count++,t.sumRgb[0]+=g,t.sumRgb[1]+=i,t.sumRgb[2]+=m,t.sumLab[0]+=f[0],t.sumLab[1]+=f[1],t.sumLab[2]+=f[2],t.averageRgb=[t.sumRgb[0]/t.count,t.sumRgb[1]/t.count,t.sumRgb[2]/t.count],t.averageLab=[t.sumLab[0]/t.count,t.sumLab[1]/t.count,t.sumLab[2]/t.count],h=!0;break}}h||e.push({count:1,sumRgb:[g,i,m],sumLab:[f[0],f[1],f[2]],averageRgb:[g,i,m],averageLab:[f[0],f[1],f[2]]})}return e}}();