出海副业logo
出海副业chuhaifuye.com

如何把 sanity 上的图片改成 webp 格式

HappyApril 12, 2025

default-image

使用Sanity CMS时,您会发现图片默认以原始格式(PNG/JPG)提供,这会导致:

  • 文件体积过大
  • 页面加载缓慢
  • 带宽浪费
  • 用户体验不佳

解决方式

根据官方文档如下:

Set auto=format to automatically return an image in in the most optimized format supported by the browser as determined by its Accept header. To achieve the same result in a non-browser context, use the fm parameter instead to specify the desired format, for example fm=webp.

Sanity图片API支持自动格式转换,只需在图片URL后添加以下参数 auto=format&fm=webp 即可。

比如:

# 转换前
https://cdn.sanity.io/images/项目ID/production/图片ID.jpg

# 转换前
https://cdn.sanity.io/images/项目ID/production/图片ID.jpg?auto=format&fm=webp

主要优势

  • 文件体积减小25-35%
  • 页面加载速度更快
  • 自动识别浏览器支持情况
  • 画质无损
  • auto=format参数会为支持的浏览器提供WebP格式,同时为旧版浏览器保留原始格式作为降级方案。

官方参考文档