Colors
適用於圖像,返回使用簡單直方圖方法的最主導顏色切片。
Syntax
RESOURCE.Colors
Returns
[]images.Color
Resource 圖像對象上的 Colors 方法返回圖像中最主導顏色的切片,從最主導到最不主導排序。此方法很快,但如果您同時縮小圖像尺寸,可以通過從縮放後的圖像提取顏色來提高性能。
方法
每個顏色是一個具有以下方法的對象:
ColorHex
(string) 返回 十六進制顏色 值,以井號前綴。
Luminance
(float64) 返回 sRGB 顏色空間中顏色的 相對亮度,范圍為 [0, 1]。值 0 表示最暗的黑色,而值 1 表示最亮的白色。
圖像濾鏡如 images.Dither、images.Padding 和 images.Text 接受十六進制顏色值或 images.Color 對象作為參數。
Hugo 將 images.Color 對象渲染為十六進制顏色值。
排序
作為人為示例,創建一個圖像主導顏色的表格,最主導顏色在前,並顯示每個主導顏色的相對亮度:
{{ 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 將其渲染為:
| ColorHex | 相對亮度 |
|---|---|
#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>這是深色背景上的淺色文本。</p>
</div>
</div>
{{ end }}WCAG 對比度比率
在上一個示例中,我們將淺色文本放在深色背景上,但這種顏色組合是否符合 WCAG 指南的 最低 或 增強 對比度比率?
WCAG 將 對比度比率 定義為:
其中 $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 "對比度比率 %.2f 符合 WCAG AAA 級。" $cr }}
{{ else if ge $cr 4.5 }}
{{ printf "對比度比率 %.2f 符合 WCAG AA 級。" $cr }}
{{ else }}
{{ printf "對比度比率 %.2f 不符合 WCAG 指南。" $cr }}
{{ end }}
{{ end }}