SquishPixel Blog · Image optimisation · Image formats · Tools

Convert CMYK JPEG uploads to sRGB with sharp, not with a formula

According to DEV Community, a CMYK JPEG (a print-style colour format that uses ink channels) needs a proper ICC conversion to sRGB before it goes on a web page. An ICC profile is the data that says which colour each ink mix produces. The author reports that the Node image library sharp already does this conversion by default: .jpeg(), .webp() and .avif() output all come out as 3-channel sRGB.

The author warns against converting pixels by hand with the popular formula that derives red, green and blue from cyan, magenta, yellow and black. On the test file, that formula was off by 27.52 levels per channel on average and by 130 levels at worst. Some 94.9% of the 480,000 pixels had at least one channel more than 10 levels away from sharp's ICC conversion. The author says the formula ignores the profile entirely.

Detection is simple. sharp can report the colour space and channel count from metadata before decoding, and the author suggests logging this to see how often CMYK files arrive. The author made a test file with toColourspace('cmyk'). Its embedded print profile was 961,644 bytes, two thirds of the file. After conversion, the output carried a 480-byte sRGB profile instead.

The suggested upload step converts to sRGB and keeps a small sRGB profile so browsers read the colours consistently. On the test file it produced an 89,228-byte JPEG and took 55.0 ms for an 800 × 600 image at quality 90. The author keeps an explicit toColourspace('srgb') call so the intent survives later code changes.

The author notes limits. A round trip from sRGB to CMYK and back lost some colour (a mean difference of 17.50) because colours outside the CMYK range get clipped. Files from Photoshop with SWOP or FOGRA profiles were not tested, and perceptual colour difference was not measured. The author also builds Blinkimg, an image compressor, and wrote the piece with help from an AI assistant.

Why it matters

If your site accepts image uploads from designers, agencies or stock libraries, some of them will be CMYK. Sent to browsers as they are, they carry a large print profile and may show colours differently. Hand-written pixel maths looks like a quick fix but, per this test, shifts colours across the whole picture.

The good news is that the default behaviour of a common library already handles the conversion. The work is mostly in not overriding it and in knowing which uploads are CMYK. Note this is one author's test on one synthetic file, so real print files may behave differently.

Source: DEV Community. This brief summarises their reporting; read the original for the full detail.