How to recolor a white-on-transparent image to an arbitrary color using CSS?

a 夏天 提交于 2021-02-08 06:51:12

问题


How do I take a image with just white and transparent pixels (example) and recolor to, say, red or orange, using only CSS?

Question below was asked previously -

Change color of PNG image via CSS?

The answer says to use filters, but does not indicate what combination of filters would make it work. Are there any filter combinations that would allow me to change a white-on-transparent image to red?


To clarify: I would like to recolor the white portion of the image, not color the background. For example, I would like it red-on-transparent.

img {
  -webkit-filter: brightness(50%) saturate(200%) hue-rotate(90deg);
  }
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f4/White_Globe_Icon.png/600px-White_Globe_Icon.png"></img>

回答1:


I played around a bit and found a possible solution to only paint the white parts:

img {
  display: block;
  background: black;
  -webkit-filter: brightness(.5);
}
.recolor {
  position: relative;
  display: inline-block;
  -webkit-filter: brightness(1) contrast(300%) invert(1);
}
.recolor:after {
  content: "";
  display: block;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 255, 255, 0.3);
}
<figure class="recolor">
  <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f4/White_Globe_Icon.png/200px-White_Globe_Icon.png">
</figure>

How it works:

  1. Make image background black and set its brightness to a half, to make the foreground gray
  2. Create a wrapper element (<figure>) and create an overlay (:after) of the inverted color you wish with a relatively low opacity
  3. Now filter the wrapper element: make it so bright with such high contrast, that the background becomes black, but the foreground color remains.
  4. Now just invert the wrapper to get your foreground color on white

Limits: Transparency gets lost, due to filtering the colors are maybe not exactly the colors you want, browser support is not optimal




回答2:


It IS possible to "colorise" a white image using filters but the results are imperfect.

The first step is a sepia filter and then a hue-rotate.

A true "Red" may be harder to achieve but you can play with this further.

img {
  max-height: 100vh;
  width: auto;
  -webkit-filter: 
    sepia(100%) 
    saturate(2000%) 
    hue-rotate(222deg);
}
body {
  background: green;
}
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f4/White_Globe_Icon.png/600px-White_Globe_Icon.png"></img>



回答3:


Just give background color to image, For Example below.

Use this image

NOTE: Image is transparent

CSS

img{
    background-color: red;
}

HTML

<img src="test.png">


来源:https://stackoverflow.com/questions/38801665/how-to-recolor-a-white-on-transparent-image-to-an-arbitrary-color-using-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!