Average color of an image with psColor.js

psColor.js – get the average color of an image

When you want to know the average color of an image, for example when you want to set the backgroundcolor of your website to the average color of an image showing in front of it, you can use psColor.js.
This is a little framework which does all the work for you.
How can I implement this framework?
– Download psColor.js or psColor.min.js. Place it in your <head> like this: <script src='psColor.js'></script>.
– Call ps.color.getImageAverageColor(imageElement) where imageElement is an <img> that has completed loading, and is on the same domain as the web page.
– ps.color.getImageAverageColor will return an object with three methods that will give you the average color in rgb, rgba, and hex:
toStringRgb (e.g. 255,128,0)
toStringRgba (e.g. 255,128,0,0.5)
toStringHex (e.g. FF8000)

Example of average color in an image

This is the psColor.js code:

(function(n){"use strict";var t=n.ps=n.ps||{};t.color={};t.color.getImageAverageColor=function(n,t){var f,v,c;if(!n)return!1;t=t||{};var s={tooDark:(t.tooDark||.03)*765,tooLight:(t.tooLight||.97)*765,tooAlpha:(t.tooAlpha||.1)*255},h=n.width,r=n.height,l=document.createElement("canvas").getContext("2d");l.drawImage(n,0,0,h,r);var o=l.getImageData(0,0,h,r).data,u={r:0,g:0,b:0,a:0},e=0,i={r:0,g:0,b:0,a:0},a=0;for(f=0,v=h*r*4;f<v;f+=4)i.r=o[f],i.g=o[f+1],i.b=o[f+2],i.a=o[f+4],i.a>s.tooAlpha&&(a=i.r+i.g+i.b)>s.tooDark&&a<s.tooLight&&(u.r+=i.r,u.g+=i.g,u.b+=i.b,u.a+=i.a,e++);return c={r:null,g:null,b:null,a:null},e>0&&(c={r:Math.round(u.r/e),g:Math.round(u.g/e),b:Math.round(u.b/e),a:Math.round(u.a/e)}),{channels:c,toStringRgb:function(){var n=this.channels;return[n.r,n.g,n.b].join(", ")},toStringRgba:function(){var n=this.channels;return[n.r,n.g,n.b,n.a].join(", ")},toStringHex:function(){var n=function(n){return r=Math.round(n).toString(16),r.length<2&&(r="0"+r),r},t=this.channels;return[n(t.r),n(t.g),n(t.b)].join("")}}}})(this);

For more info, check https://github.com/pseudosavant/psColor

Have fun with this small framework!

Leave a Reply

Your email address will not be published. Required fields are marked *