跳至主要内容

[note] 網頁圖片優化工具 Image

使用 WebP​

一般圖片​

<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>

背景圖片​

背景圖片的使用可以搭配 Modernizr 這個輕量的工具,選擇要支援的特性後,複製貼上即可使用。

當瀏覽器有支援 webp 時,會在 <html> 加上 .webp 的 class;若瀏覽器不支援,則會加上 .no-webp 的 class。

Webp:將圖片轉成 WebP 的工具​

下載​

# 透過 brew 安裝
$ brew install webp

轉檔​

# 單檔轉換
$ cwebp -q 50 images/flower1.jpg -o images/flower1.webp

# 批次轉檔
$ `for file in images/*; do cwebp -q 50 "$file" -o "${file%.*}.webp"; done`

dwebp:將 WebP 轉成其他圖片的工具​

dwebp @ Google Developers

其他實用工具​

優化圖片工具​

ImageOptim

安裝​

$ brew install --cask imageoptim

使用​

$ open -a ImageOptim . # 優化資料夾內所有檔案
$ open -a ImageOptim *.png # 優化某一支檔案

alias​

# 加到 ~/.zshrc 中,執行 imageOptim 即可對該資料夾內的所有圖片轉檔
alias imageOptim="open -a ImageOptim ."

WebPQuickLook:在 Mac 上可以預覽 WebP 圖片​

WebpQuickLook @ Github

# 透過 brew cask 安裝
$ brew install --cask WebPQuickLook

方便在 Mac 上檢視 WebP 的圖片。

PNGQuant:優化 PNG 的 CLI 工具​

$ brew install pngquant
# 加到 ~/.zshrc 中,執行 createWebp 即可對該資料夾內的所有圖片轉檔
alias createWebp='for file in ./*; do cwebp -q 50 "$file" -o "${file%.*}.webp"; done'