Get average color of image via Javascript

后端 未结 12 2189
终归单人心
终归单人心 2020-11-22 17:01

Not sure this is possible, but looking to write a script that would return the average hex or rgb value for an image. I know it can be done in AS

12条回答
  •  囚心锁ツ
    2020-11-22 17:45

    All-In-One Solution

    I would personally combine Color Thief along with this modified version of Name that Color to obtain a more-than-sufficient array of dominant color results for images.

    Example:

    Consider the following image:

    You can use the following code to extract image data relating to the dominant color:

    let color_thief = new ColorThief();
    let sample_image = new Image();
    
    sample_image.onload = () => {
      let result = ntc.name('#' + color_thief.getColor(sample_image).map(x => {
        const hex = x.toString(16);
        return hex.length === 1 ? '0' + hex : hex;
        
      }).join(''));
      
      console.log(result[0]); // #f0c420     : Dominant HEX/RGB value of closest match
      console.log(result[1]); // Moon Yellow : Dominant specific color name of closest match
      console.log(result[2]); // #ffff00     : Dominant HEX/RGB value of shade of closest match
      console.log(result[3]); // Yellow      : Dominant color name of shade of closest match
      console.log(result[4]); // false       : True if exact color match
    };
    
    sample_image.crossOrigin = 'anonymous';
    sample_image.src = document.getElementById('sample-image').src;
    

提交回复
热议问题