Skip to content

Commit 71a3d8a

Browse files
committed
dominantColor
(cherry picked from commit 8d1bd6f)
1 parent ee7b25e commit 71a3d8a

1 file changed

Lines changed: 36 additions & 1 deletion

File tree

‎ImageScript.js‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -790,6 +790,42 @@ export class Image {
790790
return Image.rgbaToColor(...colorAvg.map(v => v / divisor), 0xff);
791791
}
792792

793+
/**
794+
* Gets the images dominant color
795+
* @param {boolean} [ignoreBlack=true] Whether to ignore dark colors below the threshold
796+
* @param {boolean} [ignoreWhite=true] Whether to ignore light colors above the threshold
797+
* @param {number} [bwThreshold=0xf] The black/white threshold (0-64)
798+
* @return {number} The images dominant color
799+
*/
800+
dominantColor(ignoreBlack = true, ignoreWhite = true, bwThreshold = 0xf) {
801+
const colorCounts = new Array(0x3ffff);
802+
for (let i = 0; i < this.bitmap.length; i += 4) {
803+
const color = this.__view__.getUint32(i, false);
804+
const [h, s, l] = Image.rgbaToHSLA(...Image.colorToRGBA(color)).map(v => (~~(v * 0x3f)));
805+
if (ignoreBlack && l < bwThreshold) continue;
806+
if (ignoreWhite && l > 0x3f - bwThreshold) continue;
807+
const key = h << 12 | s << 6 | l;
808+
colorCounts[key] = (colorCounts[key] || 0) + 1;
809+
}
810+
811+
let maxColorCount = 0;
812+
let mostProminentValue;
813+
colorCounts.forEach((el, i) => {
814+
if (el < maxColorCount) return;
815+
maxColorCount = el;
816+
mostProminentValue = i;
817+
});
818+
819+
if (!mostProminentValue === undefined)
820+
return this.dominantColor(ignoreBlack, ignoreWhite, bwThreshold - 1);
821+
822+
const h = (mostProminentValue >>> 12) & 0x3f;
823+
const s = (mostProminentValue >>> 6) & 0x3f;
824+
const l = mostProminentValue & 0x3f;
825+
826+
return Image.hslaToColor(h / 0x3f, s / 0x3f, l / 0x3f, 1);
827+
}
828+
793829
/**
794830
* Rotates the image the given amount of degrees
795831
* @param {number} angle The angle to rotate the image for (in degrees)
@@ -911,7 +947,6 @@ export class Image {
911947
this.__view__ = image.__view__;
912948
this.__u32__ = image.__u32__;
913949
this.bitmap = image.bitmap;
914-
this.refs = image.refs;
915950

916951
return this;
917952
}

0 commit comments

Comments
 (0)