'Looking to extract a random color value from an image. Code type doesn't matter
So, I need a tool that will pick a random color from an image and give me the hex code for it. In specific, from an image of a 4-point gradient. I'm hoping to be able to make it so that I can load any image (by pasting in a link) and using said image, but if I have to code for a specific image edit the code each time I need a different one, that's okay too.
My thought was taking the image and randomizing between the height and width in pixels, and then selecting that pixel and getting the hex code of it, which would then be output. However, being fairly new to coding, I haven't found anything from searching online that would let me do something like this.
I have played around in JS fiddle for a few hours, and I can get it to load an image from the web, but the actual selection of a pixel isn't something I can figure out, although I assume it's possible with so many javascript color-pickers out there.
If there's an easier way to do this with a different type of code, I'm completely open to it, I just need to be pointed in the right direction. Thanks everyone!
Solution 1:[1]
Coming back to say I figured this out. What I had been looking for (as far as javascript goes, anyway,) was converting my image to base64 and then using that to get the pixels from. Then it was just a matter of randomizing between image height and image width, and selecting the corresponding pixel.
x = Math.floor(Math.random() * img.width+1);
y = Math.floor(Math.random() * img.height+1);
I'm sure this code isn't amazing, as I relied heavily on other people's code to figure out what I was doing, but in case it helps anyone this is what the end result looks like:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Amora |