created: March 27, 2006 - modified: March 27, 2006

Problem addressed

Using Portable Network Graphics (PNG) as content in IE

One of the most annoying problems designers run in to for Win IE is it's apparent lack of support for PNG Alpha transparencies. I say "apparent" because there is a way to display PNG's properly in WIN IE 5.5+, it's just not quite automatic.

Solution

For this I rely on JavaScript to modify the page's Document Object Model (DOM) to replace <img> tags with <span> tags with the above AlphaImageLoader filter applied as an inline style, with the original PNG file as the source. The width and heigth defaults to the files actually width and height unless set in the style sheet.

01 function sf_applyPNGFilter() {  
02  if(document.all&&document.getElementById
	&&(navigator.userAgent.lastIndexOf('mac')==-1)) {
03   for(var i=0; i<document.images.length; i++) { 
04 	// loop through all the images on the page looking for PNG files.
05    o_image = document.images[i];
06    $imageName = o_image.src.toUpperCase();
07    if ($imageName.substring($imageName.length-3, $imageName.length) 
	=="PNG") {
08	/* if the image ends in PNG convert it
09	You will need to re-apply the filter any 
10	time you dynamically add content that contains a PNG file, 
11 	so if the PNG filter has not already been applied to an image, then apply it. 
12	*/
13     if(o_image.style.cssText.indexOf('AlphaImageLoader') == -1){
14      $imageID = (o_image.id) ? 'id="' 
	+ o_image.id + '" ' : '';
15      $imageClass = (o_image.className) ? 'class="' 
	+ o_image.className + '" ' : '';
16      $imageTitle = (o_image.title) ? 'title="' 
	+ o_image.title + '" ' : 'title="' + o_image.alt + '" ';
17      $imageStyle = (o_image.style.cssText) ? o_image.style.cssText + ';' : '';
18      o_image.outerHTML = '<span ' + $imageID + $imageClass + $imageTitle
	+ ' style="' + $imageStyle 
	+ ' width:' + o_image.width 
	+ 'px; height:' + o_image.height + 'px; '
	+ 'filter:progid:DXImageTransform.Microsoft.'
	+ 'AlphaImageLoader(src=\'' + o_image.src + '\');">'
 	+ '</span>';
19      i = i - 1;
20     } //if
21    } //if($imageName...)
22   } //for
23  } //if(document.all...)
24 } //sf_applyPNGFilter
25 // only run this on IE Win, 
	put script call inside of an IE 
	Downlevel-hidden conditional comment for extra security 
if(document.all&&document.getElementById&
&(navigator.userAgent.lastIndexOf('mac')==-1)) 
window.attachEvent("onload", sf_applyPNGFilter);

To make sure this is only runs on WIN IE 5.5+, I place the calling <script> tag inside of a Downlevel-hidden conditional comment statement.

<!--[if gte IE 5.5]> 
  <script src="/_interface/_javascripts/imageobjectpng.js" 
		type="text/javascript" defer></script>
<![endif]-->