python实现多文件夹下图片类型转换(png转webp)

import glob
import os
import threading

from PIL import Image    


def create_image(infile, index):
    os.path.splitext(infile)
    im = Image.open(infile)
    filePath = infile[0:infile.index("/")]
    fileName = infile[str(infile).find("/") + 1:str(infile).find('.png')]
    newFile = filePath + "/" + fileName + ".webp"
    try:
        im.save(newFile, "WEBP")
    except IOError:
        if os.path.exists(newFile + ".webp"):
            os.remove(newFile + ".webp")
    else:
        print(newFile + ".webp" + "..........ok!........")
        if os.path.exists(infile):
            os.remove(infile)
            print("........delete....." + infile + ".....ok")
    if os.path.exists(newFile) and os.path.exists(infile):
        os.remove(newFile);


def start():
    projectPath = "项目目录/app/src/main/res/"
    # projectPath=""
    filePathArr = [projectPath + 'drawable',
                   projectPath + 'drawable-mdpi',
                   projectPath + 'drawable-ldpi',
                   projectPath + 'drawable-hdpi',
                   projectPath + 'drawable-xhdpi',
                   projectPath + 'drawable-xxhdpi',
                   projectPath + 'drawable-xhdpi']
    for filePath in filePathArr:
        index = 0
        for infile in glob.glob(filePath + "/*.png"):
            if infile.endswith(".9.png"):
                print(infile + ".....not do.....")
            else:
                t = threading.Thread(target=create_image, args=(infile, index))
                t.start()
                t.join()
                index += 1
        # 删除文件,注意改上面的文件后缀名
        # print(infile)
        # if os.path.exists(infile):
        #     os.remove(infile)


if __name__ == "__main__":
    start()

猜你喜欢

转载自my.oschina.net/u/435726/blog/1623488