獲取psd對象
Turn on the visibility of layers that need to be saved
保存psd
重新獲取psd對象(Tried saving layers while manipulating visibility,不可行)
Generate a transparent image with the same length and height as the original image,Merge with layers,Save the merged layer
from psd_tools import PSDImage
from PIL import Image
import os
# 圖片融合
def mix(img1, img2, coordinator):
""" :param img1: :param img2: :param coordinator: The layer is on the transparent mapleft,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) # Generates transparent images of equal height and width
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) # Determine the coordinate position of the upper left point of the layer's transparent image
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()