Extract image RGB values

Asked

Viewed 55 times

0

I’m having difficulty extracting RGB values from an image, I can only get it 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 has to convert the URL to Base64 for linear-gradient to work.

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

The result is like this when using an image in Base64:

resultado

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"/>

1 answer

1


I tested some things here on the machine and debugging found 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 anonym within the img tag, thus:

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

    Wow, something so simple, thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.