LoginSignup
11
10

More than 3 years have passed since last update.

Python で psd ファイルを処理できるライブラリ psd-toolsについて

Last updated at Posted at 2019-11-07

Python でPSDファイルを処理できるライブラリ psd-tools

▼公式ドキュメント
https://psd-tools.readthedocs.io/en/latest/

テスト画像

今回はこちらの画像をサンプルとして使用します。3070374.jpg
Designed by Freepik

▼ダウンロード先
https://www.freepik.com/free-psd/restaurant-gift-voucher-template_5903685.htm#page=3&position=11

▼Photoshop上でみたレイヤー情報
image.png

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)

▼出力

▼example.png
example.png


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")

▼結果
Waffel.png
Orange.png
Brush Stroke.png
Tomato.png
Tomato Sauce.png
Title.png
Background.png
20% OFF.png
Web.png
Voucher ID #56893.png
Food.png

11
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
10