如何使用 CSS 将图像的颜色更改为黑白?
CSS(层叠样式表)是一种功能强大的语言,用于控制网页的视觉呈现。我们可以使用 CSS 实现的最重要的功能之一就是将网页上的图像颜色更改为黑白。
使用 CSS 将图像的颜色更改为黑白是一个简单的过程,可以使用几种不同的方法来完成。在本文中,我们将学习三种使用 CSS 将图像转换为黑白的不同方法。
方法 1 - 使用"灰度"滤镜
方法 2 - 使用"亮度"和"饱和度"滤镜
方法 3 - 使用"色相旋转"滤镜
方法 1:使用"灰度"滤镜
"灰度"滤镜是使用 CSS 将图像颜色更改为黑白的最基本和最常见的方法。此滤镜的值介于 0% 到 100% 之间,其中 0% 表示图像应为全彩色,100% 表示图像应为全黑白。可以通过将以下 CSS 代码添加到图像的 CSS 类来将此滤镜应用于图像。
语法
css-selector {
/css 代码…
}
示例
这是一个使用"灰度"滤镜在 CSS 中更改图像颜色的示例。
<html>
<title>Change the color of an image in css using a "grayscale" filter</title>
<head>
<style>
body {
text-align:center;
}
.img{
filter: grayscale(100%);
-webkit-filter: grayscale(100%);
}
</style>
</head>
<body>
<h3>Original Image</h3>
<img src="/css/images/logo.png" alt="image">
<h3>after using "grayscale" filter</h3><br>
<img class="img" src="/css/images/logo.png" alt="image">
</body>
</html>
方法二:使用"亮度"和"饱和度"滤镜
使用 CSS,"亮度"和"饱和度"滤镜是将图像转换为黑白的第二种方法。"亮度"滤镜用于调整图像的整体亮度,而"饱和度"滤镜用于调整图像的饱和度。
语法
css-selector {
filter: brightness(0.5) saturate(0%);
}
示例
以下是使用"亮度"和"饱和度"滤镜在 CSS 中更改图像颜色的示例。
<html>
<title>Change the color of an image in css using a "brightness" and "saturate" filters</title>
<head>
<style>
body {
text-align:center;
}
.img{
filter: brightness(0.5) saturate(0%);
}
</style>
</head>
<body>
<h1>Welcome to Tutorialspoint</h1>
<h3>Original Image</h3>
<img src="/css/images/logo.png" alt="image">
<h3>after using "brightness" and "saturate" filters</h3><br>
<img class="img" src="/css/images/logo.png" alt="image">
</body>
</html>
方法 3:使用"hue-rotate"滤镜
"hue-rotate"滤镜用于旋转图像的色调,可将图像转换为黑白。
语法
css-selector {
filter: hue-rotate(180deg);
}
示例
以下是使用"hue-rotate"滤镜在 CSS 中更改图像颜色的示例。
<html>
<title>Change the color of an image in css using a "hue-rotate" filters</title>
<head>
<style>
body {
text-align:center;
}
.img{
filter: hue-rotate(180deg);
}
</style>
</head>
<body>
<h1>Welcome to Tutorialspoint</h1>
<h3>Original Image</h3>
<img src="https://images.unsplash.com/photo-1611825715408-826f2b19c43f?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=200&ixlib=rb1.2.1&q=80&w=200"" alt="image">
<h3>after using "hue-rotate" filters</h3><br>
<img class="img" src="https://images.unsplash.com/photo-1611825715408-826f2b19c43f?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=200&ixlib=rb1.2.1&q=80&w=200"" alt="image">
</body>
</html>
结论
使用 CSS 将图像转换为黑白图像是一个简单的过程,可以使用几种不同的技巧来完成。"灰度"滤镜、"亮度"滤镜和"饱和度"滤镜以及"色相旋转"滤镜都是完成此效果的有效方法。
相关文章
有用资源
css 参考教程 - 该教程包含有关 css 的更多信息:https://www.cainiaomax.com/css/

