Python でPSDファイルを処理できるライブラリ psd-tools
▼公式ドキュメント
https://psd-tools.readthedocs.io/en/latest/
テスト画像
今回はこちらの画像をサンプルとして使用します。
Designed by Freepik
▼ダウンロード先
https://www.freepik.com/free-psd/restaurant-gift-voucher-template_5903685.htm#page=3&position=11
psd-tools の使い方
インストール
pip install psd-tools numpy scipy
使い方
from psd_tools import PSDImage
if __name__ == '__main__':
file_path = '/Users/[uesr_name]/Downloads/restaurant-gift-voucher-template/3074963.psd'
psd = PSDImage.open(file_path)
psd.compose().save('example.png')
for layer in psd:
print(layer)
▼出力
Group('Background' size=1772x886)
Group('Design' size=1426x570)
Group('Images' size=1226x1196)
Group('Text' size=1627x443)
Group('Logo' size=386x107)
すべてのレイヤーにアクセスしたい場合
descendants() メソッドを使うことで、フォルダを含めすべてのレイヤーにアクセス可能
for layer in list(psd.descendants()):
print(layer)
Group('Background' size=1772x886)
SolidColorFill('Background' size=1772x886 mask effects)
Group('Design' size=1426x570)
SmartObjectLayer('Brush Stroke' size=1426x413 effects)
ShapeLayer('Rectangle' size=460x80 effects)
Group('Images' size=1226x1196)
SmartObjectLayer('Waffel' size=675x954 effects)
SmartObjectLayer('Food' size=23x27 effects)
SmartObjectLayer('Food' size=23x27 effects)
SmartObjectLayer('Food' size=27x27 effects)
SmartObjectLayer('Tomato Sauce' size=211x208 effects)
SmartObjectLayer('Tomato' size=237x239 effects)
SmartObjectLayer('Orange' size=276x272 effects)
Group('Text' size=1627x443)
TypeLayer('Title' size=506x122)
TypeLayer('20% OFF' size=441x96)
TypeLayer('Voucher ID #56893' size=379x30)
TypeLayer('Web' size=728x27)
TypeLayer('Address')
Group('Logo' size=386x107)
SmartObjectLayer('Place Your Logo Here (Double Click to Edit)' size=386x107)
すべてのレイヤーを PIL.Image 化してレイヤー名で保存
for layer in list(psd.descendants()):
print("layer_name: ", layer.name)
print("is_group(): ", layer.is_group())
if not layer.is_group():
pil_img = layer.topil()
pil_img.save(layer.name + ".png")