是否有一个简单的方法来显示一个彩色位图的灰度与只是HTML/CSS?
它不需要与ie兼容(我想它也不会)——如果它能在FF3和/或Sf3中工作,那对我来说就足够了。
我知道我可以用SVG和Canvas来做,但现在看起来工作量很大。
真的有懒人能做到的方法吗?
是否有一个简单的方法来显示一个彩色位图的灰度与只是HTML/CSS?
它不需要与ie兼容(我想它也不会)——如果它能在FF3和/或Sf3中工作,那对我来说就足够了。
我知道我可以用SVG和Canvas来做,但现在看起来工作量很大。
真的有懒人能做到的方法吗?
当前回答
在Internet Explorer中使用filter属性。
在webkit和Firefox中,目前还没有办法仅用CSS来降低图像的饱和度。 所以你需要使用画布或SVG作为客户端解决方案。
但我认为使用SVG更优雅。看看我的博客文章,SVG解决方案,同时适用于Firefox和webkit: http://webdev.brillout.com/2010/10/desaturate-image-without-javascript.html
严格来说,因为SVG是HTML,所以解决方案是纯HTML +css:-)
其他回答
对于Firefox,您不需要创建filter.svg文件,您可以使用数据URI方案。
第一个答案的css代码给出:
filter: url("data:image/svg+xml;utf8,<svg%20xmlns='http://www.w3.org/2000/svg'><filter%20id='grayscale'><feColorMatrix%20type='matrix'%20values='0.3333%200.3333%200.3333%200%200%200.3333%200.3333%200.3333%200%200%200.3333%200.3333%200.3333%200%200%200%200%200%201%200'/></filter></svg>#grayscale"); /* Firefox 3.5+ */
filter: grayscale(100%); /* Current draft standard */
-webkit-filter: grayscale(100%); /* New WebKit */
-moz-filter: grayscale(100%);
-ms-filter: grayscale(100%);
-o-filter: grayscale(100%);
filter: gray; /* IE6+ */
注意将“utf-8”字符串替换为您的文件编码。
这种方法应该比其他方法快,因为浏览器不需要执行第二个HTTP请求。
如果您或其他将来面临类似问题的人愿意使用PHP。 (我知道你说HTML/CSS,但也许你已经在后端使用PHP) 下面是一个PHP解决方案:
我从PHP GD库中获得了它,并添加了一些变量来自动化这个过程…
<?php
$img = @imagecreatefromgif("php.gif");
if ($img) $img_height = imagesy($img);
if ($img) $img_width = imagesx($img);
// Create image instances
$dest = imagecreatefromgif('php.gif');
$src = imagecreatefromgif('php.gif');
// Copy and merge - Gray = 20%
imagecopymergegray($dest, $src, 0, 0, 0, 0, $img_width, $img_height, 20);
// Output and free from memory
header('Content-Type: image/gif');
imagegif($dest);
imagedestroy($dest);
imagedestroy($src);
?>
作为对其他人答案的补充,可以在FF上降低图像的饱和度,而不会出现SVG矩阵的头痛问题:
<feColorMatrix type="saturate" values="$v" />
其中$v在0和1之间。相当于filter:grayscale(50%);。
生活例子:
.desaturate { filter: url("#desaturate"); -webkit-filter: grayscale(50%); } figcaption{ background: rgba(55, 55, 136, 1); padding: 4px 98px 0 18px; color: white; display: inline-block; border-top-left-radius: 8px; border-top-right-radius: 100%; font-family: "Helvetica"; } <svg version="1.1" xmlns="http://www.w3.org/2000/svg"> <filter id="desaturate"> <feColorMatrix type="saturate" values="0.4"/> </filter> </svg> <figure> <figcaption>Original</figcaption> <img src="http://www.placecage.com/c/500/200"/> </figure> <figure> <figcaption>Half grayed</figcaption> <img class="desaturate" src="http://www.placecage.com/c/500/200"/> </figure>
MDN参考资料
在Internet Explorer中使用filter属性。
在webkit和Firefox中,目前还没有办法仅用CSS来降低图像的饱和度。 所以你需要使用画布或SVG作为客户端解决方案。
但我认为使用SVG更优雅。看看我的博客文章,SVG解决方案,同时适用于Firefox和webkit: http://webdev.brillout.com/2010/10/desaturate-image-without-javascript.html
严格来说,因为SVG是HTML,所以解决方案是纯HTML +css:-)
webkit中对本地CSS过滤器的支持已从当前版本19.0.1084.46添加
所以-webkit-filter:灰度(1)将工作,这是更容易为webkit的SVG方法…