Easy alpha transparent pngs

Native alpha transparency, as supported by Safari, Firefox, Opera et al, was one of the most popular requests to be fixed in Internet Explorer 7 . As documented elsewhere, alpha transparent PNGs can still be displayed in IE6, but to do so requires browser-specific styles to be applied.

The BritPack logo on these pages is an alpha-transparent PNG and I use a little PHP script to deliver browser-specific code to IE6 and IE5.5 and a normal image to other browsers. The normal image uses this mark-up:

<img src="proud.png" alt="BritPack" style="width:140px; height:109px" />

As explained on WebFX, IE6 and IE5.5 requires a non-standard IE-specific filter to be applied as a background image, thus the same alpha-transparent PNG can be shown in IE using this code to apply the PNG as a background to a transparent gif.

<img src="shim.gif" style="width:140px; height:109px;
filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(
src='proud.png', sizingMethod='scale')"
alt="BritPack" />

When a transparent PNG is required, I use a simple PHP function to work out which code to send the browser:

function alphapng($src, $alt) {
  $ua = $_SERVER['HTTP_USER_AGENT'];
  if (strpos($ua, "MSIE 6") OR strpos($ua, "MSIE 5.5")) {
    $imgEl .= "<img src="shim.gif"
    style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(
    src='".$src."', sizingMethod='scale');" alt="".$alt.""";
    $imgEl .= " />";
  } else {
    $imgEl .= "<img src="".$src."" alt="".$alt."" />";
  }
  return $imgEl;
}

Call the function like this:

echo alphapng("proud.png", "BritPack")

The function uses old fashioned browser detection to check for IE6 or IE5.5 to decide whether to spit out the IE-specific code or a normal img element. Simple, but handy especially if (like me) you need to display a PNG upon different coloured backgrounds.