Adding alpha channels or chroma keys to JPEG images

The GIF image format supports transparency, whilst PNG supports translucency, but neither are particularly good for photos. A work around is to use the HTML5 canvas 2D context. The chroma-key.js library automatically applies alpha channels or chroma keys for all images with the associated attributes. The class and id attributes are copied to the generated canvas elements, so if you load the library before your script that adds event handlers all will be well, likewise for style rules that match the id or class values, but note that the img element will have been replaced by a canvas element. To support accessibility, the image's alt attribute is copied to the content of the canvas element. The data- prefix is used here as per the HTML5 specification support for custom attributes.


A JPEG image with a radial alpha channel. This uses a gray scale JPEG for the alpha channel.

<img src="town.jpg" data-alpha="alpha.jpg" alt="town">

A jpeg with a chroma key for transparency. This uses a photo taken against a green screen. Note that the chroma key is a color represented using the standard hex or rgb formats.

<img src="cat.jpg" data-chroma-key="#1fff15" data-delta="50" alt="cat">

Note that an alternative approach for this is to use GIF or PNG8, both of which support 8 bit indexed color palettes plus transparency. This can produce reasonable results depending upon the original image. The following PNG8 file is 8.8kB, which compares with 6.6 kB for the original JPEG image

cat as PNG8

GIF and PNG8 can be used to simulate translucency with dithering. The quality of the result will depend on the original image and what it overlays. By way of comparison here is the same image as earlier, this time as as an RGBA PNG file (size 288.8 kB), and a PNG8 file with dithered transparency (size 80.3kB). The orginal JPEG is 85.6 kB, and the grey scale PNG 4.2 kB).

town as RGBA PNG town as dithered PNG8

My thanks to Kornel for suggesting the comparison with PNG8. Note that I used gimp to generate the grey scale alpha file, and pngquant for the PNG8 files.

Creative Commons Licence This work is licensed under a Creative Commons Attribution 3.0 Unported License.
Dave Raggett <> March 2013