Get average color of image via Javascript

后端 未结 12 2043
终归单人心
终归单人心 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:36

    There is a online tool pickimagecolor.com that helps you to find the average or the dominant color of image.You just have to upload a image from your computer and then click on the image. It gives the average color in HEX , RGB and HSV. It also find the color shades matching that color to choose from. I have used it multiple times.

    0 讨论(0)
  • 2020-11-22 17:38

    First: it can be done without HTML5 Canvas or SVG.
    Actually, someone just managed to generate client-side PNG files using JavaScript, without canvas or SVG, using the data URI scheme.

    Second: you might actually not need Canvas, SVG or any of the above at all.
    If you only need to process images on the client side, without modifying them, all this is not needed.

    You can get the source address from the img tag on the page, make an XHR request for it - it will most probably come from the browser cache - and process it as a byte stream from Javascript.
    You will need a good understanding of the image format. (The above generator is partially based on libpng sources and might provide a good starting point.)

    0 讨论(0)
  • 2020-11-22 17:40

    I would say via the HTML canvas tag.

    You can find here a post by @Georg talking about a small code by the Opera dev :

    // Get the CanvasPixelArray from the given coordinates and dimensions.
    var imgd = context.getImageData(x, y, width, height);
    var pix = imgd.data;
    
    // Loop over each pixel and invert the color.
    for (var i = 0, n = pix.length; i < n; i += 4) {
        pix[i  ] = 255 - pix[i  ]; // red
        pix[i+1] = 255 - pix[i+1]; // green
        pix[i+2] = 255 - pix[i+2]; // blue
        // i+3 is alpha (the fourth element)
    }
    
    // Draw the ImageData at the given (x,y) coordinates.
    context.putImageData(imgd, x, y);
    

    This invert the image by using the R, G and B value of each pixel. You could easily store the RGB values, then round up the Red, Green and Blue arrays, and finally converting them back into an HEX code.

    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2020-11-22 17:49

    Less accurate but fastest way to get average color of the image with datauri support:

    function get_average_rgb(img) {
        var context = document.createElement('canvas').getContext('2d');
        if (typeof img == 'string') {
            var src = img;
            img = new Image;
            img.setAttribute('crossOrigin', ''); 
            img.src = src;
        }
        context.imageSmoothingEnabled = true;
        context.drawImage(img, 0, 0, 1, 1);
        return context.getImageData(1, 1, 1, 1).data.slice(0,3);
    }
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题