PNG Images with Alpha Transparency

Internet Explorer does not support 24-bit PNG images with alpha transparency, as has been well documented around the Web (here are just a few: 1, 2, 3, 4). The crux of the "solution" to this problem is to use an Internet Explorer filter called AlphaImageLoader. AlphaImageLoader can be applied to a div element to display a PNG image properly using DirectX.

The difficult part of the problem is that AlphaImageLoader applies to div elements, whereas we need to use standard img elements on other browsers. Among other things, img elements size automatically when the image downloads, but div elements have to be sized explicitly with CSS.

Many of the solutions above are geared towards fixing static HTML. With Ajax apps, you generally construct HTML elements programmatically. This recipe is optimized for that approach:

function createPNGImage(src, width, height) {
    if (navigator.userAgent.indexOf("MSIE") != -1) {
        var element = document.createElement("div");
        element.style.filter = "progid:DXImageTransform.Microsoft." +
                               "AlphaImageLoader(src='" + src + "')";
    } else {
        var element = document.createElement("img");
        element.src = src;
    }
    element.style.width = width + "px";
    element.style.height = height + "px";
    return element;
}

The createPNGImage function returns a DOM element - a different node type depending on the user's browser. Example usage:

var element = createPNGImage("example.png", 312, 33);
document.getElementById("output").appendChild(element);

See the example

Comments

Beware, IE6 is destroying the alpha filter when the element is moved from one parent to another.

Better (imo of course) to use a htc file to fix this IE6 issue.
Laurent: HTC files require a separate request to the web server, which degrades application performance quite a bit. For high performance apps, HTC files are almost always a bad solution because they require an additional, typically blocking request to the server.
What about the display of the
Tif with JEPG compressed format?
This site uses transparent PNG's to create a Vista style aero look:

http://www.ilovetorrent.nl
Thanks m8, brilliant..
HTC files are an ok hack...but why not just use transparent GIFs and save yourselves some headaches. IE is a crappy browser. live with dat
But the problem of gif images is low quality than png.

Write a Comment