Extract RGB image values

0

I am having difficulty extracting RGB values from an image, I can only if the image URL is in base64, I tried to use some functions here from the OS but without success.

The example below is working perfectly, but you have to convert the URL to base64 for linear-gradient to work.

How do I apply the effect to jpg images, png ...

The result looks like this when using a base64 image:

var rgb = getAverageRGB(document.getElementById('imgcolor'));
document.body.style.backgroundImage = 'linear-gradient(90deg, rgb('+rgb.r+','+rgb.g+','+rgb.b+')40%, rgb('+rgb.g+','+rgb.b+','+rgb.r+')100%)';

function getAverageRGB(imgEl) {
    
    var blockSize = 5,
        defaultRGB = {r:55,g:55,b:55},
        canvas = document.createElement('canvas'),
        context = canvas.getContext && canvas.getContext('2d'),
        data, width, height,
        i = -4,
        length,
        rgb = {r:0,g:0,b:0},
        count = 0;
        
    if (!context) {
        return defaultRGB;
    }
    
    height = canvas.height = imgEl.naturalHeight || imgEl.offsetHeight || imgEl.height;
    width = canvas.width = imgEl.naturalWidth || imgEl.offsetWidth || imgEl.width;
    
    context.drawImage(imgEl, 0, 0);
    
    try {
        data = context.getImageData(0, 0, width, height);
    } catch(e) {
        return defaultRGB;
    }
    
    length = data.data.length;
    
    while ( (i += blockSize * 4) < length ) {
        ++count;
        rgb.r += data.data[i];
        rgb.g += data.data[i+1];
        rgb.b += data.data[i+2];
    }
    
    rgb.r = ~~(rgb.r/count);
    rgb.g = ~~(rgb.g/count);
    rgb.b = ~~(rgb.b/count);
    
    return rgb;
}
body img {
    display: block;
    margin: 0 auto;
    width: 250px;
    height: 250px
}
<img id="imgcolor" src="https://image.tmdb.org/t/p/w185/lHu1wtNaczFPGFDTrjCSzeLPTKN.jpg"/>
    
asked by anonymous 16.11.2018 / 07:48

1 answer

1

I tested some things here on the machine and debugging I discovered that the existing error is this

Uncaught DOMException: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.

To solve, just enable CORS as anonymous within the img tag, thus:

<img id="imgcolor" crossorigin="Anonymous" src="https://image.tmdb.org/t/p/w185/lHu1wtNaczFPGFDTrjCSzeLPTKN.jpg"/>
    
19.11.2018 / 20:23