7

Is it possible to determine if a given image is grayscale or color using JavaScript?

devnull
  • 93
  • 1
  • 5
  • Use the canvas element, and loop through all pixels, and check the R=G=B. – Gerben Nov 30 '11 at 16:59
  • here's some [code to analyze](http://stackoverflow.com/questions/2541481/get-average-color-of-image-via-javascript) image colors in jscript, might help your further! – Leon Nov 30 '11 at 16:59
  • @Leon - jscript and javascript are to different languages, though you link is a javascript answer. – Ash Burlaczenko Nov 30 '11 at 17:04
  • @AshBurlaczenko - sorry but JS, JavaScript, JScript are used to talk about the JAVASCRIPT programming language. If you mean JScript.NET, that is indeed a different one ;-) – Leon Nov 30 '11 at 17:06
  • @Leon - JScript was developed by mircosoft, and JavaScript orginally by Netscape. http://javascript.about.com/od/reference/a/jscript.htm – Ash Burlaczenko Nov 30 '11 at 17:09

2 Answers2

5
  1. draw image to canvas

  2. loop through image data

  3. test for each pixel if red-cahnnel == green-channel == blue-channel (all color-channels have the same value)

if true for all pixels it is grayscale, if you hit the first pixel that does not meat the condition you can stop and it is color.

zuloo
  • 1,310
  • 1
  • 8
  • 12
  • yeah, right only in HTML5 (or browsers supporting the canvas object), but would it make sens to know if an image is grayscale if you cant do anything with the image then? if you only want to display a meta-information of the used colorspace on a website you could use some server-side program like imagemagick or some java stuff to determine the colorspace. – zuloo Dec 01 '11 at 10:25
3

Take a look at http://www.pixastic.com/lib/docs/actions/colorhistogram/

This will easily provide the data you need to determine this.

tkone
  • 22,092
  • 5
  • 54
  • 78
  • Perfect! I found that if the image is grayscale, the RGB values returned are the same. For example, a grayscale image will return something like (9445,534,501,508,442,448...) for the rvals, (9445,534,501,508,442,448...) for the gvals and (9445,534,501,508,442,448...) for the bvals. On the other hand, a color image will return (1,3,5,3,8...), (1,2,3,0,3...) and (1,2,3,0,3...) respectively. Thanks a TON for your help! – devnull Dec 01 '11 at 15:11
  • Here is the cheap solution using that library: (I give up on trying to format. I'm a frickin noob. Shoot me. Someone will fix this. Sorry for my ignorance.) function isGrayscale(img) { var histret = {}; Pixastic.process(document.getElementById(img), "colorhistogram", {paint:true, returnValue:histret}); return ((histret.rvals.toString() == histret.gvals.toString()) && (histret.gvals.toString() == histret.bvals.toString())); } – devnull Dec 01 '11 at 15:40