Webp格式图片文件批量转换为jpg的Python脚本

整理文件时发现好些图片是webp格式的,windows7下不借助其他图像软件无法直接查看。

写了个Python脚本,使用PIL,实现了Webp向jpg的批量转换。(当然也可以转换为PIL支持的其他图像格式)

运行环境:Python3 + PIL

使用方法:复制下面的脚本,保存到后缀名为 .py 的文件中,

直接拖动需要转换的Webp图像文件放到刚才保存到 .py 文件上释放,就可以了。

from PIL import Image
import os

def get_file_name(file_name):
  dot_pos = file_name.rfind('.')
  
  if dot_pos == -1:
    fn = file_name
  else:
    fn = file_name[dot_pos:]

  return fn


  return file_name[:file_name.rfind('.')]


def get_file_ext(file_name):
  dot_pos = file_name.rfind('.')
  
  if dot_pos == -1:
    ext = ''
  else:
    ext = file_name[dot_pos:]

  return ext


def webp_to_jpg(file_name, remove_webp=False):
  try:
    im = Image.open(file_name)

    new_name = get_file_name(file_name) + '.jpg'
    im.save(new_name)

    if remove_webp:
      os.remove(file_name)
  except:
    pass
  
  return
  

def list_webp(path):
  print("Get webp image files ... ", end='')
  
  files = os.listdir(path)

  webp_files = []

  for f in files:
    if os.path.isdir(f):
      continue

    if get_file_ext(f).lower() == '.webp':
      webp_files.append(f)

  print("%s found"%len(webp_files))
  return webp_files


def process(path):
  webp_files = list_webp(path)

  print("Convert webp to jpg:")
        
  for f in webp_files:
    print("\t%s"%f)
    webp_to_jpg(f, True)

  print("Done.")
  return


    index += 1
 
 
if __name__ == "__main__":
  import sys

  if len(sys.argv) > 1:
    for n in range(1, len(sys.argv, 1):
      webp_to_jpeg(sys.argv[n], True)

​

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值