系統已為您安裝 Webp 指令列工具,因此您可以開始使用。這項工具會將 JPG、PNG 和 TIFF 圖片轉換為 WebP。
將圖片轉換為 WebP 檔
- 按一下「Remix to Edit」即可編輯專案。
- 按一下「終端機」 (注意:如果「終端機」按鈕未顯示,你可能需要使用「全螢幕」選項)。
- 輸入以下指令:
cwebp -q 50 images/flower1.jpg -o images/flower1.webp
這個指令會以 50
的品質進行轉換 (0
是最差;100
是最差),images/flower1.jpg
檔案並將其儲存為 images/flower1.webp
。
完成之後,控制台中會顯示類似下方的內容:
Saving file 'images/flower1.webp'
File: images/flower1.jpg
Dimension: 504 x 378
Output: 29538 bytes Y-U-V-All-PSNR 34.57 36.57 36.12 35.09 dB
(1.24 bpp)
block count: intra4: 750 (97.66%)
intra16: 18 (2.34%)
skipped: 0 (0.00%)
bytes used: header: 116 (0.4%)
mode-partition: 4014 (13.6%)
Residuals bytes |segment 1|segment 2|segment 3|segment 4| total
macroblocks: | 22%| 26%| 36%| 17%| 768
quantizer: | 52 | 42 | 33 | 24 |
filter level: | 16 | 9 | 6 | 26 |
您已成功將圖片轉換為 WebP。
然而,像一次執行 cwebp
指令,需要較長的時間來轉換許多圖片。如果需要這樣做,可以改用指令碼。
- 在控制台中執行這個指令碼 (切勿忘記倒引號):
`for file in images/*; do cwebp -q 50 "$file" -o "${file%.*}.webp"; done`
這個指令碼能以 50
的品質進行轉換,並將 images/
目錄中的所有檔案儲存為新檔案 (相同檔案名稱,但副檔名為 .webp
) 並儲存在相同目錄中。
✔✔ 簽到
images/
目錄中現在應該會有 6 個檔案:
flower1.jpg
flower1.webp
flower2.jpg
flower2.webp
flower3.png
flower3.webp
接著,更新這個 Glitch,向支援 WebP 的瀏覽器提供 WebP 圖片。
使用 <picture>
標記新增 WebP 圖片
<picture>
標記可讓您將 WebP 提供至較新的瀏覽器,同時繼續支援舊版瀏覽器。
- 將
index.html
中的<img src="images/flower1.jpg"/>
替換為下列 HTML:
<picture>
<source type="image/webp" srcset="images/flower1.webp">
<source type="image/jpeg" srcset="images/flower1.jpg">
<img src="images/flower1.jpg">
</picture>
- 接著,將
flower2.jpg
和flower3.png
的<img>
標記替換為<picture>
標記。
✔✔ 簽到
完成後,index.html
中的 <picture>
標記應如下所示:
<picture>
<source type="image/webp" srcset="images/flower1.webp">
<source type="image/jpeg" srcset="images/flower1.jpg">
<img src="images/flower1.jpg">
</picture>
<picture>
<source type="image/webp" srcset="images/flower2.webp">
<source type="image/jpeg" srcset="images/flower2.jpg">
<img src="images/flower2.jpg">
</picture>
<picture>
<source type="image/webp" srcset="images/flower3.webp">
<source type="image/png" srcset="images/flower3.png">
<img src="images/flower3.png">
</picture>
接著,使用 Lighthouse 驗證是否已在網站正確實作 WebP 圖片。
透過 Lighthouse 驗證 WebP 使用情形
Lighthouse 的以新一代格式提供圖片效能稽核可讓您瞭解網站上的所有圖片是否都使用 WebP 等新一代格式。
- 如要預覽網站,請按下「View App」,然後按下「Fullscreen」。
- 按下 Control+Shift+J 鍵 (或在 Mac 上為 Command+Option+J 鍵) 開啟開發人員工具。
- 按一下「Lighthouse」分頁標籤。
- 確認您已在「類別」清單中勾選「成效」核取方塊。
- 按一下「產生報表」按鈕。
- 確認已通過提供新一代格式的圖片稽核結果。
大功告成!目前在網站上提供 WebP 圖片。