使用指令列建立 WebP 圖片

Katie Hempenius
Katie Hempenius

webp 指令列工具已預先安裝,您可以直接開始使用。這項工具可將 JPG、PNG 和 TIFF 圖片轉換為 WebP。

將圖片轉換為 WebP 檔

  1. 按一下「重混即可編輯」,即可編輯專案。
  2. 按一下「終端機」 (注意:如果沒有看到「終端機」按鈕,可能需要使用「全螢幕」選項)。
  3. 輸入以下指令:
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 等新一代格式。

  1. 如要預覽網站,請按下「View App」,然後按下「Fullscreen」全螢幕。
  2. 按下 `Control+Shift+J` (在 Mac 上為 `Command+Option+J`) 開啟開發人員工具。
  3. 按一下「Lighthouse」分頁標籤。
  4. 確認已在「類別」清單中勾選「效能」核取方塊。
  5. 按一下「產生報表」按鈕。
  6. 確認「以新一代格式提供圖片」稽核已通過。

通過 Lighthouse 的「採用新一代格式提供圖片」稽核

太好了,現在,您的網站會放送 WebP 圖片。