Get average color of image via Javascript

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

提交回复
热议问题