Hard Rock Hallelujah!

The Problem With PNGs

The Problem With PNGs - Comments

Friday 26th August 2005

Categories: Guides, Internet, Code

All comments not written by free-bees.co.uk are owned by the author, and free-bees.co.uk is in no way responsible for their content.

1. Submitted by Mathew Roblin, Friday 2nd September 2005

I have explored this, one of the numerous headaches attached to IE. There is a working method to use PNGs with full transparency in web pages for IE5.5+, by using CSS behaviours to manage the image. If you have a look at the HTC file, below:

---------------------Start <public:component>
<public:attach event="onpropertychange" onevent="propertyChanged()" />
<script> var supported = /MSIE (5\.5)|[6789]/.test(navigator.userAgent) &&
navigator.platform == "Win32";
var realSrc;
var blankSrc = "/blank.gif"; if (supported) fixImage(); function propertyChanged() {
if (!supported) return; var pName = event.propertyName;
if (pName != "src") return;
// if not set to blank
if ( ! new RegExp(blankSrc).test(src))
fixImage();
}; function fixImage() {
// get src
var src = element.src; // check for real change
if (src == realSrc) {
element.src = blankSrc;
return;
} if ( ! new RegExp(blankSrc).test(src)) {
// backup old src
realSrc = src;
} // test for png
if ( /\.png$/.test( realSrc.toLowerCase() ) ) {
// set blank image
element.src = blankSrc;
// set filter
element.runtimeStyle.filter =
"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src +
"',sizingMethod='scale')";
}
else {
// remove filter
element.runtimeStyle.filter = "";
}
} </script>
</public:component> ---------------------------- End

When you insert the terms "img{behavior: url(nameoffile.htc); }" in the style tag of the HTML file or your CSS file; for IE, the htc behaviour replaces every instance of PNG in the file with a transparent gif file (which you would have prepared in advance). The behaviour then uses the DirectX Behaviour "AlphaImageLoader" to overlay the PNG file (with full transparency) over the blank gif file: hey presto, full alpha transparency. I can't take the credit, though. This is something I found after a lot of MSDN searching a long while ago. Whoever first applied this method deserves a medal. Now all that needs to happen is for IE to be fully CSS2.0 compliant.

2. Submitted by Mike, free-bees.co.uk, Friday 2nd September 2005

In response to #1:

Although I haven't tried this solution, it certainly looks interesting, and may be useful to some people. But remember - you use this at your own risk!