春江暮客

春江暮客的个人学习分享网站

python将全站图片改为webp格式

2018-12-04 技术
python将全站图片改为webp格式

如果你关注网页加载速度,图片格式通常是最容易优化的一环。WebP 由 Google 推出,同时支持有损和无损压缩,在大多数网站场景里都能明显减小图片体积。

对于站点图片较多的情况,用 Python 批量转成 WebP 会比手工一张张处理方便很多。下面就用 Pillow 演示如何把 JPG、JPEG、PNG 等图片转换成 WebP。

第一步:安装Pillow包

pip install Pillow

第二步:开始转换为webp

from PIL import Image

imagePath = "bingchuan.jpg" #读入文件名称

outputPath = "bingchuan.webp" #输出文件名称
im = Image.open(imagePath) #读入文件
im.size #可查看图片大小<br>
im.thumbnail((1200,900), Image.ANTIALIAS) #重新设置图片大小<br>im.save(outputPath) #保存<br>

如果你使用的是较新的 Pillow 版本,Image.ANTIALIAS 可能已经被替换为新的重采样写法,这时可以改成 Image.Resampling.LANCZOS。

bingchuan

第三步:批量转换图片为webp


from PIL import Image
from os import walk
def pic_webp(picpath):
    imagePath = picpath.split(".")[0] 
#文件名称
    outputPath = imagePath + ".webp" 
#输出文件名称
    im = Image.open(imagePath) 
#读入文件<br>
    im.save(outputPath)
 #保存<br>
for (dirpath,dirname,dirfile) in os.walk("./"):
    if dirfile.split(".")[1] in ["png","jpeg","jpg"]:
        pic_webp(dirpath+"/"+dirfile)

简简单单几句代码就可以把当前目录下的 PNG、JPEG、JPG 图片批量转换成 WebP。真正应用到整站时,除了文件本身要转换,你还要同步处理数据库或文章内容里的图片路径。

实际操作时建议先备份原图,再批量转换。这样如果某些主题、插件或旧浏览器兼容策略需要回退,处理起来会安全很多。

标签

1024 12306 2fa ablang adsense agents.md ai ai-agent ai-agents ai-seo algorithm amp antibodies apparmor argparse automation backup bash batch-processing binarycif bioinformatics biopython blockchain boltz bootstrapping boxes bubblewrap c-index cca cdn chatgpt checkpoint cli cloudflare codex cofoldarena concurrency configparser configuration copy cprofile cpu监控 cron csv cuda curl data-leakage data-processing data-quality data-validation datascience datavisualization datetime debugging decimal deployment desktop-app devtools difflib disk-space disown dns docker dovecot download electron encoding esm esm2 esm3 esmc esmfold2 etag evaluation faceswap fasta fastmcp faulthandler ffmpeg file-descriptors file-io file-management files flashppi flask folium frontend game generator git github-actions google google-research gpt-6.1-sol grep gzip harness heapq hls html http hugo imports indexnow ipaddress jailbreak javascript jev json jsonl just k-means kaggle langfuse leecode linux list litellm llm llms.txt logging logs lollipop lsof m3u8 machine-learning macos manacher matplotlib mcp memory mirror mmcif model-evaluation monitoring mp3 mp4 mpnn multiomics mutation mysql nanobert nanobodies networking networkx nginx normalize numpy ollama omegatherm pandas password pathlib pdb pep-723 performance permissions phaser pillow pip postfix preprocessing print prompt-engineering protein-alignment protein-design protein-embeddings protein-interactions protein-language-models protein-stability protein-structure proxy pydantic pyecharts pyqt python python3 r raincloud reproducibility requests reservoir-sampling rfoptimization rg ripgrep rosettafold3 roundcube rrsi rsi rsync s-tui sampling scale scikit-learn scrapy screen seaborn security selenium seo sequence-identity sha256 shell signals sitemap sklearn socket solana somaticsignatures sorting spl sqlite ssh standardize static-site subprocess symlink sysadmin system-one tarfile tcp tempfile tensorflow tkinter tls toml totp tracemalloc tron tronpy troubleshooting turtle typesafe-ai ubuntu unicode urllib usdt utf-8 uv venv vhhbert vite web-tools webp wordcloud wordpress workflow xml yaml zipfile zoneinfo 后台 寓言 概率 经济 贸易 迅雷解析 钱包

友情链接

其它