Colors
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 會將其渲染為:
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 定義了 對比比率 為:
$$contrast\ ratio = { 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 }}