end0tknr's kipple - web写経開発

太宰府天満宮の狛犬って、妙にカワイイ

Pillow for python による画像downloadと png形式での保存

先程のentryの続きです。

  • step 1 request.urlopen() で画像をdownloadし
  • step 2 io.BytesIO()で file化し
  • step 3 Pillow にて png形式で保存

します

#!/usr/local/bin/python3
# -*- coding: utf-8 -*-

from PIL import Image
from urllib import request
import io
import re
import sys

def main():

    urls_file_path = sys.argv[1]
    re_compile = re.compile("https?://([^/]+)")

    img_hosts = {}
    with open(urls_file_path) as f:
        for url in f.readlines():
            url = url.strip()

            re_result = re_compile.search( url )
            if not re_result:
                continue

            hostname = re_result.group(1).replace('.','_')
            if not hostname in img_hosts:
                img_hosts[hostname] = 0

            img_hosts[hostname] += 1
            save_file_path = "./img/%s_%03d.png" % (hostname,img_hosts[hostname])

            try:
                img_content = request.urlopen(url).read()
            except Exception as e:
                print(e, file=sys.stderr)
                continue
            
            with io.BytesIO( img_content ) as f:
                try:
                    img = Image.open(f)
                except Exception as e:
                    print(e, file=sys.stderr)
                    continue
                
                img.save( save_file_path)

if __name__ == '__main__':
    main()