HudsonPH HudsonPH - 5 months ago 218
Javascript Question

How to get image color mode (CMYK, RGB ...) in Javascript

can the JavaScript check the color mode of a image?

I did a lot of search about this but the only thing I saw was color mode convert (but the convert wants you to set the original color mode)




I add this:
--allow-file-access-from-files
to have a full control of img in canvas beacause I am using GoogleChrome

Html

<canvas id="canvas" width=6000 height=7919></canvas>


Js

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var img = new Image();
img.crossOrigin = "anonymous";
img.onload = start;
img.src = "file:///D:/vincent-van-gogh-the-starry-night-picture-157544-2.png";

K3N K3N
Answer

Can the JavaScript check the color mode of a image?

Yes and no.

No if you use ordinary image loading. All images that are supported by the browser are converted to RGB(A) before they are handed to us through the Image object (HTMLImageElement).

At this point no information about the original format and color model is presented except from its size and origin.

Canvas only deals with RGBA as all other elements that are displayed and there exist no native method to address color models such as CMYK.

You could always read the RGBA values and convert to CMYK naively, however, without a ICC profile for the target printer you would run into all sort of problems due to the wider gamut of RGB, and printer as well as print medium characteristics which must be adjusted for through ICC profiles. Meaning the result will not produce correct colors in most cases.

You would have to have a server-side solution setup for this to work. Send image to server, convert to CMYK/apply ICC, then send to printer. ImageMagick could be one way to go about it. The browser is simply not cut (nor intended) for print oriented processing.

Yes if you're willing to write image parser manually as well as ICC parser. You would need to support a variety of formats and format combinations, and also be able to apply ICC/gamma on import as well as export to CMYK through the target ICC (meaning you need to support XYZ/LAB color spaces).

The export would require you to write a file writer supporting the CMYK color space and ICC embedding.

The maturing process, bugs, instabilities etc. would be a natural part of the process and likely not something you would want to use in production right away.

If you're just after the color mode of the file and can load the image like ordinary you can of course load the file first through XHR, then scan the file using typed array to locate the information describing the color format depending on format. Then pass the typed array as Blob -> object-URL to load as an image, go through canvas and convert each pixel to CMYK values.

But from this point you will have the same problems as described above and would not escape writing the file writer etc.