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

2022-10-29 11:27:31

整理文件时发现好些图片是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)

  • 作者:farmanlinuxer
  • 原文链接:https://blog.csdn.net/farmanlinuxer/article/details/82683362
    更新时间:2022-10-29 11:27:31