import os
import sys
import time
import _thread
import PIL.Image as Image

threadNum_dealPng = 0

# 将PNG图片背景色设置为透明
def dealPng(pngFile):
    global threadNum_dealPng

    threadNum_dealPng += 1

    img = Image.open(pngFile).convert('RGBA')   # 从RGB（24位）模式转成RGBA（32位）模式
    W, L = img.size
    # targetColor = (128,128,128,255)  # 待替换掉的背景颜色
    targetColor = (95,235,140,255)  # 待替换掉的背景颜色
    for h in range(W):
        for i in range(L):
            # print(img.getpixel((h, i)))
            if img.getpixel((h, i)) == targetColor:
                # img.putpixel((h, i), (0, 0, 0, 0))   # 设置透明
                img.putpixel((h, i), (0, 0, 0, 153))   # 设置半透明
    img.save(pngFile)  # 自己设置保存地址
    # img.save(pngFile + '.png')  # 自己设置保存地址

    threadNum_dealPng -= 1


def dealAllPng(rootdir):
    for root,dirs,files in os.walk(rootdir):
        # for dir in dirs:
        #     print(os.path.join(root,dir))
        for file in files:
            print("dealAllPng: " + os.path.join(root,file))
            dealPng(os.path.join(root,file))
            # _thread.start_new_thread(dealPng, (os.path.join(root,file),))
            # time.sleep(0.3)


if __name__ == '__main__':
    paramNum = len(sys.argv)
    if paramNum != 2:
        print("param err! please input fileid.")
        exit()

    # sys.argv[0] 表示脚本名
    fileid = int(sys.argv[1])      #csv文件编号  详见 fileinfo.js
    filepath =  r"pic\\%d" % fileid

    # dealPng(filepath + "\\00003_141535_3.png")

    print("dealAllPng start !")
    dealAllPng(filepath)
    
    time.sleep(0.1)
    while 1:
        if threadNum_dealPng == 0:
            print("dealAllPng finished !")
            break
        else:
            print("dealAllPng threadNum_dealPng: %d" % threadNum_dealPng)
            time.sleep(1)

