Erik Lenaerts

Do, or do not. There is no try.

ASP.NET fix for the Microsoft Internet Explorer PNG transparancy bug

Introduction

When working with Internet Explorer 5.5 or higher and you want to use PNG images that make use of the Alpha channel for transparancy effects, you will get unwanted effects. In fact Internet Explorer does not support the transparancy features of the PNG image format unless you use a trick. If you search on google on this topic, you'll find a lot of detailed information like over here.

ASP.NET Solution

Although most solutions found on the web, requires the use of javascript, we provide a server side solution in ASP.NET based on one method you just have to call from every ASP.NET page that makes use of PNG images like:

//Fix PNG bug of MSIE
FixMSIEPNGBug(this);

The method below will scan the entire page recursivly for Images and will add the MSIE fix for properly showing the PNG image.

Note that there are minor 3 points here :

  • this method requires the use of webcontrols, so it will ignore any traditional HTML IMG tags
  • You need to have an image called spacer.png, which is 1 pixel large PNG-8 image containing binary transparency (which MSIE does support).
  • All your image tags that display a PNG image should have a height and width attribute set. Otherwise the PNG images will dissapear from the screen.

private void FixMSIEPNGBug(Control parent)
{
   
if (Request.Browser.Type.ToUpper().IndexOf("IE") >= 0)
    {
       
foreach(Control ctrl in parent.Controls)
        {
           
if (ctrl is System.Web.UI.WebControls.Image)
            {
                System.Web.UI.WebControls.Image img
= ctrl as System.Web.UI.WebControls.Image;
               
if (img.ImageUrl.ToUpper().EndsWith("PNG"))
                {
                    img.Style[
"filter"] = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + img.ImageUrl + "', sizingMethod='scale');";
                    img.ImageUrl
= "images/spacer.png";
                }
            }
           
           
//Recurse
            FixMSIEPNGBug(ctrl);
        }
    }
}

- Erik

Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: