CSS过滤器:使透明白色的彩色图像

时间:2014-06-14 20:40:59

标签: css css-filters

我有一个透明的彩色png图像。我想使用css过滤器使整个图像变白,但保持透明度不变。 这可能在CSS中吗?

2 个答案:

答案 0 :(得分:271)

您可以使用

filter: brightness(0) invert(1);

html {
  background: red;
}
p {
  float: left;
  max-width: 50%;
  text-align: center;
}
img {
  display: block;
  max-width: 100%;
}
.filter {
  -webkit-filter: brightness(0) invert(1);
  filter: brightness(0) invert(1);
}
<p>
  Original:
  <img src="http://i.stack.imgur.com/jO8jP.gif" />
</p>
<p>
  Filter:
  <img src="http://i.stack.imgur.com/jO8jP.gif" class="filter" />
</p>

首先,brightness(0)使所有图像变黑,透明部分除外,它们保持透明。

然后,invert(1)使黑色部分变白。

答案 1 :(得分:5)

据我所知,遗憾的是没有CSS滤镜可以对元素进行着色(可能使用了一些SVG滤镜魔法,但我对此有点不熟悉),即使不是这样的,过滤器基本上只受webkit浏览器的支持。

话虽如此,您仍然可以解决此问题,并使用canvas修改您的图片。基本上,您可以将图像元素绘制到画布上,然后循环遍历像素,将相应的RGBA值修改为您想要的颜色。

然而,画布确实有一些限制。最重要的是,您必须确保图像src来自与页面相同的域。否则,浏览器不允许您读取或修改画布的像素数据。

这里有JSFiddle更改JSFiddle徽标的颜色。

&#13;
&#13;
//Base64 source, but any local source will work
var src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAC0AAAAgCAYAAACGhPFEAAAABGdBTUEAALGPC/xhBQAABzhJREFUWAnNWAtwXFUZ/v9zs4GUJJu+k7tb5DFAGWO1aal1sJUiY3FQQaWidqgPLAMqYzd9CB073VodhCa7KziiFgWhzvAYQCiCD5yK4gOTDnZK2ymdZoruppu0afbu0pBs7p7f7yy96W662aw2QO/Mzj2P//Gd/5z/+89dprfzubnTN332Re+xiKawllxWucm+9O4eCi9xT8ctn45yKd3AXX1BPsu3XIiuY+K5kDmrUA7jORb5m2baLm7uscNrJr9eOF9Je8JAz9ySnFHlq9nEpG6CYx+RdJD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aAMT2+/Vlfzp81/vywLMWSBN1QAAAABJRU5ErkJggg==";
var canvas = document.getElementById("theCanvas");
var ctx = canvas.getContext("2d");
var img = new Image;

//wait for the image to load
img.onload = function() {
    //Draw the original image so that you can fetch the colour data
    ctx.drawImage(img,0,0);
    var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    
    /*
    imgData.data is a one-dimensional array which contains 
    the respective RGBA values for every pixel 
    in the selected region of the context 
    (note i+=4 in the loop)
    */
    
    for (var i = 0; i < imgData.data.length; i+=4) {
			imgData.data[i] = 255; //Red, 0-255
			imgData.data[i+1] = 255; //Green, 0-255
			imgData.data[i+2] = 255; //Blue, 0-255
			/* 
			imgData.data[i+3] contains the alpha value
			which we are going to ignore and leave
			alone with its original value
			*/
    }
    ctx.clearRect(0, 0, canvas.width, canvas.height); //clear the original image
    ctx.putImageData(imgData, 0, 0); //paint the new colorised image
}

//Load the image!
img.src = src;
&#13;
body {
    background: green;
}
&#13;
<canvas id="theCanvas"></canvas>
&#13;
&#13;
&#13;