From SVG
This solution uses a browser to parse/extract all colors present. You should follow this steps:
The idea is iterating over all elements and using getComputedStyle(), then extract only values like rgb(n, n, n)
using a regex like /(.*)(rgb([0-9, ]*))(.*)/g
performing another loop, like this:
var doc = document.getElementsByTagName("*");
var colors = [];
for (let j = 0; j < doc.length; j++) {
var styles = window.getComputedStyle(doc[j], null)
for (let i = 0; i < styles.length; i++) {
if (typeof styles[styles[i]] !== "undefined" && styles[styles[i]].match(/rgb([0-9, ]*)/g)) {
let color = styles[styles[i]].replace(/(.*)(rgb([0-9, ]*))(.*)/g,"$2")
if (!colors.includes(color))
colors.push(color);
}
}
}
console.log(colors)
Full functional example here: https://jsfiddle.net/gwd35Lyv/ and https://jsfiddle.net/oenmL4t6/ an empty document in which you could include the svg created.
This is assuming we are using a browser, not embebed JavaScript into illustrator file.
You could also open the svg file with a browser, like this https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/AJ_Digital_Camera.svg press F12 and in the console, paste the js code in it.
From Image
Previous solution doesn't compute the colors present in images, because we have to read pixel by pixel, to do that based in this How to get a pixel's x,y coordinate color from an image?. we could do this:
var img = document.getElementById('my-image');
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
var rect = img.getBoundingClientRect();
var colors = [];
for (let y = rect.top; y <= rect.left; y++) {
for (let x = rect.left; x <= rect.right; x++) {
var pixelData = canvas.getContext('2d').getImageData(x, y, 1, 1).data;
var rgb = "rgb(" + pixelData[0] + ", " + pixelData[1] + ", " + pixelData[2] + ")"
if (!colors.includes(rgb)) {
colors.push(rgb);
}
}
}
console.log(colors)
Here an example: http://jsfiddle.net/vkq0ew9n/ The restriction is that the image should be within the same origin (local doesn't work, just http: https: etc, not file:).