This is about "Color Quantization" that has several approachs like MMCQ (Modified Median Cut Quantization) or OQ (Octree Quantization). Different approach use K-Means to obtain clusters of colors.
I have putted all together here, since I was finding a solution for tvOS
where there is a subset of XHTML, that has no <canvas/>
element:
Generate the Dominant Colors for an RGB image with XMLHttpRequest