-
-
Save qodesmith/beba97d13a9ab81360ed39598c9fc37c to your computer and use it in GitHub Desktop.
Get the average colour of an image in javascript using getImageData in CANVAS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function getAverageColourAsRGB (img) { | |
| var canvas = document.createElement('canvas'), | |
| context = canvas.getContext && canvas.getContext('2d'), | |
| rgb = {r:102,g:102,b:102}, | |
| pixelInterval = 5, | |
| count = 0, | |
| i = -4, | |
| data, length; | |
| if (!context) { alert('Your browser does not support CANVAS'); return rgb; } | |
| var height = canvas.height = img.naturalHeight || img.offsetHeight || img.height, | |
| width = canvas.width = img.naturalWidth || img.offsetWidth || img.width; | |
| context.drawImage(img, 0, 0); | |
| try { | |
| data = context.getImageData(0, 0, width, height); | |
| } catch(e) { | |
| alert(e); | |
| return rgb; | |
| } | |
| data = data.data; | |
| length = data.length; | |
| while ((i += pixelInterval * 4) < length) { | |
| count++; | |
| rgb.r += data[i]; | |
| rgb.g += data[i+1]; | |
| rgb.b += data[i+2]; | |
| } | |
| rgb.r = Math.floor(rgb.r/count); | |
| rgb.g = Math.floor(rgb.g/count); | |
| rgb.b = Math.floor(rgb.b/count); | |
| return rgb; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment