利用python一键将webp格式图片转换为png或者jpg

目录

1、博客介绍

2、内容

.主体内容

.批处理一键调用

3、推送

4、结语


1、博客介绍

最近从网页上摘下来的资源有好多webp格式的图片,需要转为png或jpg,之前也没怎么看过python,稍微看了一下写了个小工具,能够将同级目录下所有webp格式的图片全部转为png或者jpg,博主是在python2.7环境下做的开发,效果如下:


2、内容

.主体内容

直接上代码吧,没啥绕的,就是检索目录下所有的webp然后转为png,保存后再把原图给删了,代码中注释很全


# 功能 : 将当前工作目录下所有webp格式转为png or jpg
# -*- coding: UTF-8 -*-
import os
from PIL import Image

# 返回当前工作目录
CURRENT_PATH = os.getcwd()

# 转换格式
IMG_EXP = ".png"

# 获取最高所有文件
cur_all_files   = os.listdir(CURRENT_PATH)
# 转换列表
imgList         = []

# 遍历文件夹,储存webp格式的路径到列表内
def findFileForImage(filePath):
    child_all_files = os.listdir(filePath)
    for child_file_name in child_all_files:
    	sPath = os.path.join(filePath, child_file_name)
    	if os.path.isdir(sPath):
    		findFileForImage(sPath)
    	n,e = os.path.splitext(child_file_name)
    	if e.lower() == ".webp":
    		imgList.append(os.path.join(filePath, n))


# 检索目录下所有的webp文件,如果是文件夹则继续向下检索
for file_name in cur_all_files:
    nPath = os.path.join(CURRENT_PATH, file_name)
    # 文件夹
    if os.path.isdir(nPath):
    	findFileForImage(nPath)
        continue
    # 储存
    name, ext = os.path.splitext(file_name)
    if ext.lower() == ".webp":
        imgList.append(os.path.join(CURRENT_PATH, name))


# 转换图片
def convertImage():
	for webpPath in imgList:
		print(webpPath)

		# 打开图片并赋值一份新的图片
		img = Image.open(webpPath+".webp")
		img.load()
		# 将赋值的图片修改后缀保存在原路径
		img.save(webpPath+IMG_EXP)
		# 删除原webp图
		os.remove(webpPath+".webp")

# 执行
convertImage()


.批处理一键调用

这里做个批处理文件直接一键调用

@echo off


rem %0         代指批处理文件自身
rem %~d0       是指批处理所在的盘符
rem %~dp0      是盘符加路径

rem cd %~dp0   就是进入批处理所在目录了
 
echo local_cap  
C:  
cd %~dp0
start python ConvertImage.py 
rem 使用ping命令暂停3s,这样可以看到调用python后的结果
::ping -n 10 127.0.0.1 > nul 

3、推送

源码:https://github.com/KingSun5/WebpToPngByPython


4、结语

若是觉得博主的文章写的不错,不妨关注一下博主,点赞一下博文,另博主能力有限,若文中有出现什么错误的地方,欢迎各位评论指摘。

       QQ交流群:806091680(Chinar)

       该群为CSDN博主Chinar所创,推荐一下!我也在群里!

       本文属于原创文章,转载请著名作者出处并置顶!!!!
 

猜你喜欢

转载自blog.csdn.net/Mr_Sun88/article/details/106303440