颜色
Syntax
RESOURCE.Colors
Returns
[]images.Color
Resources.Colors
方法返回图像中最主要颜色片段,按从最主要到最次要的顺序排列。此方法速度很快,但是如果同时缩小图像尺寸,则可以通过从缩放后的图像中提取颜色来提高性能。
方法
每种颜色都是具有以下方法的对象:
- ColorHex
- New in v0.125.0
- (
string
) 返回带有井号前缀的 十六进制颜色 值。 - Luminance
- New in v0.125.0
- (
float64
) 返回 sRGB 颜色空间中颜色的 相对亮度 ,范围为 [0, 1]。值0
表示最暗的黑色,而值1
表示最亮的白色。
排序
作为一个牵强的例子,创建一个图像主要颜色的表格,最主要的颜色排在首位,并显示每种主要颜色的相对亮度:
{{ with resources.Get "images/a.jpg" }}
<table>
<thead>
<tr>
<th>颜色</th>
<th>相对亮度</th>
</tr>
</thead>
<tbody>
{{ range .Colors }}
<tr>
<td>{{ .ColorHex }}</td>
<td>{{ .Luminance | lang.FormatNumber 4 }}</td>
</tr>
{{ end }}
</tbody>
</table>
{{ end }}
Hugo 渲染结果为:
颜色 | 相对亮度 |
---|---|
#bebebd |
0.5145 |
#514947 |
0.0697 |
#768a9a |
0.2436 |
#647789 |
0.1771 |
#90725e |
0.1877 |
#a48974 |
0.2704 |
要按优势排序,最不重要的颜色排在首位:
{{ range .Colors | collections.Reverse }}
要按相对亮度排序,最暗的颜色排在首位:
{{ range sort .Colors "Luminance" }}
要按相对亮度排序,最亮的颜色排在首位,可以使用以下任一结构:
{{ range sort .Colors "Luminance" | collections.Reverse }}
{{ range sort .Colors "Luminance" "desc" }}
示例
图片边框
要使用最主要的颜色为图像添加 5 像素的边框:
{{ with resources.Get "images/a.jpg" }}
{{ $mostDominant := index .Colors 0 }}
{{ $filter := images.Padding 5 $mostDominant }}
{{ with .Filter $filter }}
<img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="">
{{ end }}
{{ end }}
要使用最暗的主要颜色为图像添加 5 像素的边框:
{{ with resources.Get "images/a.jpg" }}
{{ $darkest := index (sort .Colors "Luminance") 0 }}
{{ $filter := images.Padding 5 $darkest }}
{{ with .Filter $filter }}
<img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="">
{{ end }}
{{ end }}
深色背景上的浅色文本
要创建一个文本框,其中前景和背景颜色来自图像中最浅和最暗的主要颜色:
{{ with resources.Get "images/a.jpg" }}
{{ $darkest := index (sort .Colors "Luminance") 0 }}
{{ $lightest := index (sort .Colors "Luminance" "desc") 0 }}
<div style="background: {{ $darkest }};">
<div style="color: {{ $lightest }};">
<p>This is light text on a dark background.</p>
</div>
</div>
{{ end }}
WCAG 对比度比率
在前面的示例中,我们将浅色文本放在深色背景上,但是这种颜色组合是否符合 WCAG 指南中关于 最小 或 增强 对比度比率的准则?
WCAG 将 对比度比率 定义为:
$$对比度比率 = { L_1 + 0.05 \over L_2 + 0.05 }$$其中 $L_1$ 是最浅颜色的相对亮度,$L_2$ 是最暗颜色的相对亮度。
计算对比度比率以确定 WCAG 一致性:
{{ with resources.Get "images/a.jpg" }}
{{ $lightest := index (sort .Colors "Luminance" "desc") 0 }}
{{ $darkest := index (sort .Colors "Luminance") 0 }}
{{ $cr := div
(add $lightest.Luminance 0.05)
(add $darkest.Luminance 0.05)
}}
{{ if ge $cr 7.5 }}
{{ printf "The %.2f contrast ratio conforms to WCAG Level AAA." $cr }}
{{ else if ge $cr 4.5 }}
{{ printf "The %.2f contrast ratio conforms to WCAG Level AA." $cr }}
{{ else }}
{{ printf "The %.2f contrast ratio does not conform to WCAG guidelines." $cr }}
{{ end }}
{{ end }}