Поддержка прозрачности PNG в IE6
Многие из вас, наверняка, сталкивались с прелестями браузера Internet Explorer. Наверняка, Вы даже сталкивались с его «великолепной» поддержкой полупрозрачных PNG файлов. Вот и мы столкнулись с подобной проблемой. Недолгие поиски привели к решению, которым мы с Вами и делимся. Точнее, было найдено даже два решения. Какое их них использовать - выбирать Вам.
Решение номер ноль
Все нижеприведенные решения по сути предназначены для пакетной обработки картинок. Но, по сути, для кажой картинки делается следующее:
-
<img src="test.png" width="247" height="216" style="filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='test.png', sizingMethod='scale');" alt="" />
А теперь...
Решение номер один - чиним со стороны клиента
Вся прелесть этой технологии заключается в том, что она распространяется даже на бэкграунды, обозначенные в CSS'е. Все, что Вам нужно сделать, это скачать маленький zip-архив, скопировать файлы из архива в Вашу директорию, и в CSS'е прописать всего лишь одну строчку:
-
* { behavior: url(iepngfix.htc); }
У этой строчки есть небольшой минус – сильно влияет на скорость отображения (рендеринга) сайта, поэтому можете использовать более точные указания, например:
-
img { behavior: url(iepngfix.htc); }
или, например:
-
img, #id { behavior: url(iepngfix.htc); }
Как этим воспользоваться – в Ваших руках, идея, надеюсь, Вам понятна.
Желаю удачи в Ваших проектах! Постоянный читатель Тмба
Решение номер два - чиним на стороне сервера
-
/**
-
* KOIVI PNG Alpha IMG Tag Replacer for PHP (C) 2004 Justin Koivisto
-
* Version 2.0.12
-
* Last Modified: 12/30/2005
-
*
-
* This library is free software; you can redistribute it and/or modify it
-
* under the terms of the GNU Lesser General Public License as published by
-
* the Free Software Foundation; either version 2.1 of the License, or (at
-
* your option) any later version.
-
*
-
* This library is distributed in the hope that it will be useful, but
-
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
-
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
-
* License for more details.
-
*
-
* You should have received a copy of the GNU Lesser General Public License
-
* along with this library; if not, write to the Free Software Foundation,
-
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
*
-
* Full license agreement notice can be found in the LICENSE file contained
-
* within this distribution package.
-
*
-
* Justin Koivisto
-
* justin.koivisto@gmail.com
-
* http://koivi.com
-
*
-
* Modifies IMG and INPUT tags for MSIE5+ browsers to ensure that PNG-24
-
* transparencies are displayed correctly. Replaces original SRC attribute
-
* with a binary transparent PNG file (spacer.png) that is located in the same
-
* directory as the orignal image, and adds the STYLE attribute needed to for
-
* the browser. (Matching is case-insensitive. However, the width attribute
-
* should come before height.
-
*
-
* Also replaces code for PNG images specified as backgrounds via:
-
* background-image: url(image.png); or background-image: url('image.png');
-
* When using PNG images in the background, there is no need to use a spacer.png
-
* image. (Only supports inline CSS at this point.)
-
*
-
* @param string $x String containing the content to search and replace in.
-
* @param string $img_path The path to the directory with the spacer image relative to
-
* the DOCUMENT_ROOT. If none os supplied, the spacer.png image
-
* should be in the same directory as PNG-24 image.
-
* @param string $sizeMeth String containing the sizingMethod to be used in the
-
* Microsoft.AlphaImageLoader call. Possible values are:
-
* crop - Clips the image to fit the dimensions of the object.
-
* image - Enlarges or reduces the border of the object to fit
-
* the dimensions of the image.
-
* scale - Default. Stretches or shrinks the image to fill the borders
-
* of the object.
-
* @param bool $inScript Boolean flag indicating whether or not to replace IMG tags that
-
* appear within SCRIPT tags in the passed content. If used, may cause
-
* javascript parse errors when the IMG tags is defined in a javascript
-
* string. (Which is why the options was added.)
-
* @return string
-
*/
-
function replacePngTags($x,$img_path='',$sizeMeth='scale',$inScript=FALSE){
-
// make sure that we are only replacing for the Windows versions of Internet
-
// Explorer 5.5+
-
$msie='/msie\s(5\.[5-9]|[6]\.[0-9]*).*(win)/i';
-
return $x;
-
-
if($inScript){
-
// first, I want to remove all scripts from the page...
-
for($i=0;$i<count($scripts[0]);$i++){
-
$saved_scripts[]=$scripts[0][$i];
-
$placeholders[]='replacePngTags_ScriptTag-'.$i;
-
}
-
}
-
-
// find all the png images in backgrounds
-
for($i=0;$i<count($background[0]);$i++){
-
// simply replace:
-
// "background-image: url('image.png');"
-
// with:
-
// "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(
-
// enabled=true, sizingMethod=scale, src='image.png');"
-
// I don't think that the background-repeat styles will work with this...
-
'Microsoft.AlphaImageLoader(enabled=true, sizingMethod='.$sizeMeth.
-
', src=\''.$background[2][$i].'\');',$x);
-
}
-
-
// find all the IMG tags with ".png" in them
-
$pattern='/<(input|img)[^>]*src=([\\"\\\']?)([^>]*\.png)\2[^>]*>/i';
-
for($num_images=0;$num_images<count($images[0]);$num_images++){
-
// for each found image pattern
-
$original=$images[0][$num_images];
-
$quote=$images[2][$num_images];
-
$atts=''; $width=0; $height=0; $modified=$original;
-
-
// We do this so that we can put our spacer.png image in the same
-
// directory as the image - if a path wasn't passed to the function
-
// this was a relative URI, image should be in this directory
-
}else{
-
$img_path.='/';
-
}
-
// in case the supplied path didn't end with a /
-
$img_path.='/';
-
}
-
-
// If the size is defined by styles, find them
-
'/style=([\\"\\\']).*(\s?width:\s?([0-9]+(px|%));).*'.
-
'(\s?height:\s?([0-9]+(px|%));).*\\1/Ui',
-
$images[0][$num_images],$arr2);
-
// size was defined by styles, get values
-
$width=$arr2[3][0];
-
$height=$arr2[6][0];
-
-
// remove the width and height from the style
-
// Also remove any empty style tags
-
'`style='.$arr2[1][0].$arr2[1][0].'`i',
-
'',
-
}else{
-
// size was not defined by styles, get values from attributes
-
$width=$arr2[2][0];
-
$width.='px';
-
-
// remove width from the tag
-
}
-
$height=$arr2[2][0];
-
$height.='px';
-
-
// remove height from the tag
-
}
-
}
-
-
if($width==0 || $height==0){
-
// width and height not defined in HTML attributes or css style, try to get
-
// them from the image itself
-
// this does not work in all conditions... It is best to define width and
-
// height in your img tag or with inline styles..
-
// image is on this filesystem, get width & height
-
$width=$size[0].'px';
-
$height=$size[1].'px';
-
// image is on this filesystem, get width & height
-
$width=$size[0].'px';
-
$height=$size[1].'px';
-
}
-
}
-
-
// end quote is already supplied by originial src attribute
-
$replace_src_with=$quote.$img_path.'spacer.png'.$quote.' style="width: '.$width.
-
'; height: '.$height.'; filter: progid:DXImageTransform.'.
-
'Microsoft.AlphaImageLoader(src=\''.$images[3][$num_images].'\', sizingMethod='.
-
$sizeMeth.');"';
-
-
// now create the new tag from the old
-
// now place the new tag into the content
-
}
-
-
if($inScript){
-
// before the return, put the script tags back in. (I was having problems when there was
-
// javascript that had image tags for PNGs in it when using this function...
-
}
-
-
return $x;
-
}
Приведенная функция обрабатывает картинки png, у которых указаны размеры, а также свойства background-image в CSS.
Не забудьте внимательно посмотреть на параметры функции. Или хотя бы положите заглушку spacer.png в ту же папку, где лежит картинка.
Кроме того необходимо учитывать, что возможны проблемы в случае, если обрабатываемая картинка является ссылкой - в результате работы функции она уходит в background. То есть надо класть блок со ссылкой поверх картинки.
Использовать это очень просто - перед тем, как отослать страницу клиенту пропускаем ее через эту функцию. В резальтате мы имеем исправленные png, но только для тех, у кого MSIE. Остальные получают код без мусора. Еще один плюс заключается в том, что мы избавляем клиента от сравнительно тяжелого JavaScript'а.


May 28th, 2007 at 20:07 Quote
Ура! ;) *радуваицо*
Но, честно говоря, все равно это не помогло, был какой-то глюк с картинкой и решили вообще перерисовать все нафиг. :-)
June 25th, 2007 at 16:21 Quote
фу, какая гадость страшная! есть намного проще способ, как мне кажеться, посредством только CSS.. :)
могу у себя написать статейку, если интересно. все равно собирался рано или поздно её написать, все забывал..
June 25th, 2007 at 17:50 Quote
вот я лапоть... пардон.. видать я не прогер - игнорировал вариант номер 0 и начал читать с номер 1... мой вариант тоже использует "AlphaImageLoader", только вместо sizingMethod='scale' - sizingMethod='crop'...
*невнимательное*
September 11th, 2007 at 17:32 Quote
Самый простой способ решения этой проблемы - вообще не использовать рисунки в формате png !
January 15th, 2008 at 17:21 Quote
иногда без них очень плохо