65.9K
CodeProject is changing. Read more.
Home

PNG alpha support for Internet Explorer

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.47/5 (11 votes)

Sep 16, 2004

viewsIcon

78785

downloadIcon

454

An article on how to implement PNG alpha support for Internet Explorer

Introduction

Internet Explorer doesn’t support the alpha channel in PNG images. However the fix is to use the "AlphaImageLoader" filter. This script replaces all PNG images on the page with a blank image (blank.gif) and adds the "AlphaImageLoader" filter with the original image source. The blank image is to avoid the "broken image" picture to display above the filter. This script also supports printing and changing the source image at runtime.

Source

//Array containing all PNG images on the page
var PNGimageArray = new Array();
var isPrinting = false;

//Path to the blank image (1x1 transparent)
var blankSrc = "blank.gif";

//Captures print events
window.attachEvent("onbeforeprint", function () { beforePrint(); } );
window.attachEvent("onafterprint", function () { afterPrint(); } );
//Tests if element is a PNG image, and if so fixes it
function addPngImage(element){
  if (/\.png$/i.test(element.src)) {
    fixImage(element);
    element.attachEvent("onpropertychange", function () 
      { propertyChanged(); } );
    PNGimageArray[PNGimageArray.length] = element;
  }
}

//Applies filter and changes source to blank
function fixImage(element) {
  element.runtimeStyle.filter = 
   "progid:DXImageTransform.Microsoft.AlphaImageLoader(
      src='" + element.src + "')";
  element.src = blankSrc;
}

//If property "src" is changed fixs image (not 
//if it is changed to blank though)
function propertyChanged() {
  if (isPrinting) return;
  var element = event.srcElement;
  var pName = event.propertyName;
  if (pName != "src") return;
  if (!new RegExp(blankSrc).test(element.src))
    fixImage(element);

}

//Turns image back to original before print (Explorer can't print filters)
function beforePrint() {
  isPrinting = true;
  var element;
  for(var i = 0; i < PNGimageArray.length; i++){
    element = PNGimageArray[i];
    element.src = element.filters[0].src;
    element.runtimeStyle.filter = "";
  }

}

//Fixes image after print
function afterPrint() {
  isPrinting = false;
  var element;
  for(var i = 0; i < PNGimageArray.length; i++){
    element = PNGimageArray[i];
    fixImage(element);

  }
}
Style that makes all images run the addPngImage function. I use "expression" instead of "behavior" to avoid some security issues in Internet Explorer.
<style type="text/css"> img { filter:expression(addPngImage(this)); }
</style>