獲取psd對象
將需要保存的圖層的可見性開啟
保存psd
重新獲取psd對象(嘗試過邊操作可見性邊保存圖層,不可行)
生成與原圖等長等高的透明圖,與圖層合並,保存合並之後的圖層
from psd_tools import PSDImage
from PIL import Image
import os
# 圖片融合
def mix(img1, img2, coordinator):
""" :param img1: :param img2: :param coordinator: 圖層在透明圖上的left,top坐標 :return: """
im = img1
mark = img2
layer = Image.new('RGBA', im.size, (0, 0, 0, 0))
layer.paste(mark, coordinator)
out = Image.composite(layer, im, layer)
return out
def change_visible():
psd_path = r'G:\20220803\全景\000001\000001_000000.psd'
psd = PSDImage.open(psd_path) # 打開psd對象
for index, layer in enumerate(psd.descendants()):
layer_name = layer.name # 圖層名稱
if layer_name.count("背景"): # 過濾掉背景
layer.visible = False
continue
layer.visible = True
psd.save(psd_path) # 保存
def get_save_layer_png():
psd_path = r'G:\20220803\全景\000001\000001_000000.psd'
basename = os.path.basename(psd_path).replace(".psd", "")
save_png_dir_path = os.path.join(os.path.dirname(psd_path), basename)
if not os.path.exists(save_png_dir_path):
os.makedirs(save_png_dir_path)
psd = PSDImage.open(psd_path) # 打開psd對象
image = Image.new(mode='RGBA', size=psd.size) # 生成等高等寬的透明圖
for index, layer in enumerate(psd.descendants()):
print(layer.size) # 圖層大小
layer_name = layer.name # 圖層名稱
if layer_name.count("背景"): # 過濾掉背景
continue
layer.composite().save("tmp.png")
file1 = Image.open("tmp.png")
co = (layer.left, layer.top) # 確定圖層透明圖左上點的坐標位置
mix_res = mix(image, file1, co)
mix_res.save(os.path.join(save_png_dir_path, layer.name + ".png"))
# print(mix_res)
os.remove("tmp.png")
if __name__ == '__main__':
change_visible()
get_save_layer_png()