Is there a way to use jQuery or Javascript to detect the colorspace of a JPG image that is being uploaded via file input? To be more accurate I need a way to kick back a response when a user attempts to upload a CMYK colorspaced JPG. I would like to catch this on the client side if at all possible. I would prefer to do this using jQuery/js, but I'm definitely open to libraries that may have this functionality. Thanks in advance for any help.
-
1Using jquery, you can load the raw image via something like $.ajax({url:image_url, dataType:"text", success:check_if_cmyk}); The first parameter passed to the function check_if_cmyk will be a string with the raw image. You then need to detect if the image is (a) a jpeg, and (b) in CMYK. A simple test might just be a check to see how many chrominance channels you have. – garlon4 Apr 29 '14 at 21:22
2 Answers
I've looked around a bit, and it seems like JavaScript could be powerful enough to do this, albeit possibly very slowly.
Here is a stackoverflow question that deals with using JavaScript for face detection: Any library for face recognition in JavaScript?
I know that doesn't answer the question specifically, but it does demonstrate that JavaScript could potentially be leveraged for what you want.
Here is a question that deals with using JS along with the canvas
object to get the average color of an image: Get average color of image via Javascript
There are some answers there that may be helpful for you. One of the answers there links to a library called Color Thief that could do what you want: https://github.com/lokesh/color-thief
If no one has already built what you want, my takeaway here is that it would be a laborious task, which may or may not yield results fast enough to be useful.

- 1
- 1

- 7,254
- 2
- 28
- 44
I had a comment that you could do a jquery ajax call to get the raw data. I don't think that is actually true, as there is no way to get the raw data. However, many browsers support the "arraybuffer" responseType of an XML http request, and you can use that. Here is a code snippet:
var img_url = "/images/testimg.jpg";
var req = new XMLHttpRequest();
req.open("GET", img_url, true);
req.responseType = "arraybuffer";
req.onload = function (event)
{
var buf = req.response;
var num_channels = null;
if (buf)
{
var img = new Uint8Array(buf);
for (var i=0; i<img.length-9; i++)
{
if (img[i]==0xFF && (img[i+1]==0xC0 || img[i+1]==0xC1))
{
var num_channels = img[i+9];
break;
}
}
}
if (num_channels==4)
console.log("This is a four-channel image.");
};
req.send(null);
Obviously, you'd want to actually do something with the result, and there should be better checking to make sure this IS a JPEG and not a random collection of bytes. Furthermore, this only will work on Baseline and Extended JPEGs, not progressive, arithmetic encoding, JPEG 2000, or anything else.
This doesn't really test if the colorspace is CMYK (or YCCK), just that it has four components, but the basic idea is there.

- 1,162
- 10
- 14