topleft topright
 

Поддержка прозрачности PNG в IE6

Печать E-mail
(0 голосов)

Источник: http://tmbu.info

Многие из вас, наверняка, сталкивались с прелестями браузера Internet Explorer. Наверняка, Вы даже сталкивались с его «великолепной» поддержкой полупрозрачных PNG файлов. Вот и мы столкнулись с подобной проблемой. Недолгие поиски привели к решению, которым мы с Вами и делимся. Точнее, было найдено даже два решения. Какое их них использовать - выбирать Вам.

Решение номер ноль

Все нижеприведенные решения по сути предназначены для пакетной обработки картинок. Но, по сути, для кажой картинки делается следующее:

HTML:
 
  1. <img src="test.png" width="247" height="216" style="filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='test.png', sizingMethod='scale');" alt="" />

 

А теперь...

Решение номер один - чиним со стороны клиента

Вся прелесть этой технологии заключается в том, что она распространяется даже на бэкграунды, обозначенные в CSS'е. Все, что Вам нужно сделать, это скачать маленький zip-архив, скопировать файлы из архива в Вашу директорию, и в CSS'е прописать всего лишь одну строчку:

CSS:
  1. * { behavior: url(iepngfix.htc); }

 

У этой строчки есть небольшой минус – сильно влияет на скорость отображения (рендеринга) сайта, поэтому можете использовать более точные указания, например:

CSS:
  1. img { behavior: url(iepngfix.htc); }

 

или, например:

CSS:
  1. img, #id { behavior: url(iepngfix.htc); }

 

Как этим воспользоваться – в Ваших руках, идея, надеюсь, Вам понятна.

Желаю удачи в Ваших проектах! Постоянный читатель Тмба

 

Решение номер два - чиним на стороне сервера

PHP:
 
  1. /**
  2. *  KOIVI PNG Alpha IMG Tag Replacer for PHP (C) 2004 Justin Koivisto
  3. *  Version 2.0.12
  4. *  Last Modified: 12/30/2005
  5. *  This library is free software; you can redistribute it and/or modify it
  6. *  under the terms of the GNU Lesser General Public License as published by
  7. *  the Free Software Foundation; either version 2.1 of the License, or (at
  8. *  your option) any later version.
  9. *  This library is distributed in the hope that it will be useful, but
  10. *  WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  11. *  or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
  12. *  License for more details.
  13. *  You should have received a copy of the GNU Lesser General Public License
  14. *  along with this library; if not, write to the Free Software Foundation,
  15. *  Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. *  Full license agreement notice can be found in the LICENSE file contained
  17. *  within this distribution package.
  18. *  Justin Koivisto
  19. Этот e-mail защищен от спам-ботов. Для его просмотра в вашем браузере должна быть включена поддержка Java-script
  20. *  http://koivi.com
  21. *
  22. *  Modifies IMG and INPUT tags for MSIE5+ browsers to ensure that PNG-24
  23. *  transparencies are displayed correctly.  Replaces original SRC attribute
  24. *  with a binary transparent PNG file (spacer.png) that is located in the same
  25. *  directory as the orignal image, and adds the STYLE attribute needed to for
  26. *  the browser. (Matching is case-insensitive. However, the width attribute
  27. *  should come before height.
  28. *  Also replaces code for PNG images specified as backgrounds via:
  29. *  background-image: url(image.png); or background-image: url('image.png');
  30. *  When using PNG images in the background, there is no need to use a spacer.png
  31. *  image. (Only supports inline CSS at this point.)
  32. *  @param string $x  String containing the content to search and replace in.
  33. *  @param string $img_path   The path to the directory with the spacer image relative to
  34. *                      the DOCUMENT_ROOT. If none os supplied, the spacer.png image
  35. *                      should be in the same directory as PNG-24 image.
  36. *  @param string $sizeMeth   String containing the sizingMethod to be used in the
  37. *                      Microsoft.AlphaImageLoader call. Possible values are:
  38. *                      crop - Clips the image to fit the dimensions of the object.
  39. *                      image - Enlarges or reduces the border of the object to fit
  40. *                              the dimensions of the image.
  41. *                      scale - Default. Stretches or shrinks the image to fill the borders
  42. *                              of the object.
  43. *  @param bool   $inScript  Boolean flag indicating whether or not to replace IMG tags that
  44. *                      appear within SCRIPT tags in the passed content. If used, may cause
  45. *                      javascript parse errors when the IMG tags is defined in a javascript
  46. *                      string. (Which is why the options was added.)
  47. *  @return string
  48. */
  49. function replacePngTags($x,$img_path='',$sizeMeth='scale',$inScript=FALSE){
  50.     $arr2=array();
  51.     // make sure that we are only replacing for the Windows versions of Internet
  52.     // Explorer 5.5+
  53.     $msie='/msies(5.[5-9]|[6].[0-9]*).*(win)/i';
  54.     if( !isset($_SERVER['HTTP_USER_AGENT']) ||
  55.         !preg_match($msie,$_SERVER['HTTP_USER_AGENT']) ||
  56.         preg_match('/opera/i',$_SERVER['HTTP_USER_AGENT']))
  57.         return $x;
  58.  
  59.     if($inScript){
  60.         // first, I want to remove all scripts from the page...
  61.         $saved_scripts=array();
  62.         $placeholders=array();
  63.         preg_match_all('`<script[^>]*>(.*)</script>`isU',$x,$scripts);
  64.         for($i=0;$i<count($scripts[0]);$i++){
  65.             $x=str_replace($scripts[0][$i],'replacePngTags_ScriptTag-'.$i,$x);
  66.             $saved_scripts[]=$scripts[0][$i];
  67.             $placeholders[]='replacePngTags_ScriptTag-'.$i;
  68.         }
  69.     }
  70.  
  71.     // find all the png images in backgrounds
  72.     preg_match_all('/background-image:s*url((["']?)([^)]+.png)1);/Uis',$x,$background);
  73.     for($i=0;$i<count($background[0]);$i++){
  74.         // simply replace:
  75.         //  "background-image: url('image.png');"
  76.         // with:
  77.         //  "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(
  78.         //      enabled=true, sizingMethod=scale, src='image.png');"
  79.         // I don't think that the background-repeat styles will work with this...
  80.         $x=str_replace($background[0][$i],'filter:progid:DXImageTransform.'.
  81.                 'Microsoft.AlphaImageLoader(enabled=true, sizingMethod='.$sizeMeth.
  82.                 ', src=''.$background[2][$i].'');',$x);
  83.     }
  84.  
  85.     // find all the IMG tags with ".png" in them
  86.     $pattern='/<(input|img)[^>]*src=(["']?)([^>]*.png)2[^>]*>/i';
  87.     preg_match_all($pattern,$x,$images);
  88.     for($num_images=0;$num_images<count($images[0]);$num_images++){
  89.         // for each found image pattern
  90.         $original=$images[0][$num_images];
  91.         $quote=$images[2][$num_images];
  92.         $atts=''; $width=0; $height=0; $modified=$original;
  93.  
  94.         // We do this so that we can put our spacer.png image in the same
  95.         // directory as the image - if a path wasn't passed to the function
  96.         if(empty($img_path)){
  97.             $tmp=split('[/]',$images[3][$num_images]);
  98.             $this_img=array_pop($tmp);
  99.             $img_path=join('/',$tmp);
  100.             if(empty($img_path)){
  101.                 // this was a relative URI, image should be in this directory
  102.                 $tmp=split('[/]',$_SERVER['SCRIPT_NAME']);
  103.                 array_pop($tmp);    // trash the script name, we only want the directory name
  104.                 $img_path=join('/',$tmp).'/';
  105.             }else{
  106.                 $img_path.='/';
  107.             }
  108.         }else if(substr($img_path,-1)!='/'){
  109.             // in case the supplied path didn't end with a /
  110.             $img_path.='/';
  111.         }
  112.  
  113.         // If the size is defined by styles, find them
  114.         preg_match_all(
  115.             '/style=(["']).*(s?width:s?([0-9]+(px|%));).*'.
  116.             '(s?height:s?([0-9]+(px|%));).*1/Ui',
  117.                $images[0][$num_images],$arr2);
  118.         if(is_array($arr2) && count($arr2[0])){
  119.             // size was defined by styles, get values
  120.             $width=$arr2[3][0];
  121.             $height=$arr2[6][0];
  122.  
  123.             // remove the width and height from the style
  124.             $stripper=str_replace(' ','s','/('.$arr2[2][0].'|'.$arr2[5][0].')/');
  125.             // Also remove any empty style tags
  126.             $modified=preg_replace(
  127.                 '`style='.$arr2[1][0].$arr2[1][0].'`i',
  128.                 '',
  129.                 preg_replace($stripper,'',$modified));
  130.         }else{
  131.             // size was not defined by styles, get values from attributes
  132.             preg_match_all('/width=(["']?)([0-9%]+)1/i',$images[0][$num_images],$arr2);
  133.             if(is_array($arr2) && count($arr2[0])){
  134.                 $width=$arr2[2][0];
  135.                 if(is_numeric($width))
  136.                     $width.='px';
  137.    
  138.                 // remove width from the tag
  139.                 $modified=str_replace($arr2[0][0],'',$modified);
  140.             }
  141.             preg_match_all('/height=(["']?)([0-9%]+)1/i',$images[0][$num_images],$arr2);
  142.             if(is_array($arr2) && count($arr2[0])){
  143.                 $height=$arr2[2][0];
  144.                 if(is_numeric($height))
  145.                     $height.='px';
  146.    
  147.                 // remove height from the tag
  148.                 $modified=str_replace($arr2[0][0],'',$modified);
  149.             }
  150.         }
  151.  
  152.         if($width==0 || $height==0){
  153.             // width and height not defined in HTML attributes or css style, try to get
  154.             // them from the image itself
  155.             // this does not work in all conditions... It is best to define width and
  156.             // height in your img tag or with inline styles..
  157.             if(file_exists($_SERVER['DOCUMENT_ROOT'].$img_path.$images[3][$num_images])){
  158.                 // image is on this filesystem, get width & height
  159.                 $size=getimagesize($_SERVER['DOCUMENT_ROOT'].$img_path.$images[3][$num_images]);
  160.                 $width=$size[0].'px';
  161.                 $height=$size[1].'px';
  162.             }else if(file_exists($_SERVER['DOCUMENT_ROOT'].$images[3][$num_images])){
  163.                 // image is on this filesystem, get width & height
  164.                 $size=getimagesize($_SERVER['DOCUMENT_ROOT'].$images[3][$num_images]);
  165.                 $width=$size[0].'px';
  166.                 $height=$size[1].'px';
  167.             }
  168.         }
  169.        
  170.         // end quote is already supplied by originial src attribute
  171.         $replace_src_with=$quote.$img_path.'spacer.png'.$quote.' style="width: '.$width.
  172.             '; height: '.$height.'; filter: progid:DXImageTransform.'.
  173.             'Microsoft.AlphaImageLoader(src=''.$images[3][$num_images].'', sizingMethod='.
  174.             $sizeMeth.');"';
  175.  
  176.         // now create the new tag from the old
  177.         $new_tag=str_replace($quote.$images[3][$num_images].$quote,$replace_src_with,
  178.             str_replace('  ',' ',$modified));
  179.         // now place the new tag into the content
  180.         $x=str_replace($original,$new_tag,$x);
  181.     }
  182.    
  183.     if($inScript){
  184.         // before the return, put the script tags back in. (I was having problems when there was
  185.         // javascript that had image tags for PNGs in it when using this function...
  186.         $x=str_replace($placeholders,$saved_scripts,$x);
  187.     }
  188.    
  189.     return $x;
  190. }

 

Приведенная функция обрабатывает картинки png, у которых указаны размеры, а также свойства background-image в CSS.

 

Не забудьте внимательно посмотреть на параметры функции. Или хотя бы положите заглушку spacer.png в ту же папку, где лежит картинка.

 

Кроме того необходимо учитывать, что возможны проблемы в случае, если обрабатываемая картинка является ссылкой - в результате работы функции она уходит в background. То есть надо класть блок со ссылкой поверх картинки.

 

Использовать это очень просто - перед тем, как отослать страницу клиенту пропускаем ее через эту функцию. В резальтате мы имеем исправленные png, но только для тех, у кого MSIE. Остальные получают код без мусора. Еще один плюс заключается в том, что мы избавляем клиента от сравнительно тяжелого JavaScript'а.

 
« Как избежать кеширования CSS   Персональный CSS хак для Internet Explorer 7 »

Украинская Баннерная Сеть
PR и тИЦ