Get average color of image via Javascript

后端 未结 12 2144
终归单人心
终归单人心 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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);
    }
    

提交回复
热议问题