Python pillow PIL で画像変換

http://pypi.python.org/pypi/Pillow/

Pillow is the “friendly” PIL fork. PIL is the Python Imaging Library. Pillow was started for and is currently maintained by the Plone community. But it is used by many other folks in the Python web community, and probably elsewhere too.

PIL forkでPILが更新されていないのでpillowで更新することが目的なようです。
中身はPILと同じなので、利用方法なども同じようです。

Build instructions (all platforms)を参考に
centosに入れてみる。

1. ライブラリ準備
jpeg
# yum install libjpeg libjpeg-devel
png
# yum install zlib zlib-devel
freetype2
# yum install freetype freetype-devel
littleCMS
# yum install lcms-devel lcms-libs python-lcms

# yum install python-devel

2. pillow install
# pip-python install pillow
Downloading/unpacking pillow
Downloading Pillow-1.7.8.zip (410Kb): 39% 163Kb

Successfully installed pillow
Cleaning up…

完了。

PILを利用してみる。

http://www.pythonware.com/library/pil/handbook/image.htm

bride.jpgを置いて、test.pyで以下を実行。

from PIL import Image
im = Image.open(“bride.jpg”)
im.rotate(45).show()

インストール確認。

ディレクトリに置いたファイル群をあるサイズに変換して出力する。
1.png 2.jpg 3.png
があるとき
1_40x40.png 1_80x80.png
2_40x40.jpg 2_80x80.jpg
3_40x40.png 3_80x80.png
とりあえず比率固定ですが、サムネイル生成のようなものが必要なので作る。

こんな感じで

#!/usr/bin/python
import os, sys
import re
from PIL import Image

width = 40
height = 40
size = width, height
fsize = “_”+str(width)+”x”+str(height)

pathname = os.path.dirname(sys.argv[1])
for infile in os.listdir( pathname ):
 if re.search(‘.png$’, infile) and not re.search( fsize, infile ):
   fname = infile.split(‘.’)
   outfile = pathname + ‘/’+ fname[0] + fsize + ‘.’ + fname[1]
   infile = pathname + ‘/’ + infile
   if infile != outfile:
     try:
       im = Image.open(infile)
       im.thumbnail(size)
       im.save(outfile, “PNG”)
     except IOError:
       print “cannot create thumbnail for”, infile

良い感じで変換出力出来ました。

調べつつ約1時間なので、同じことをやる場合は、このままで問題なければ15分かからないと思います。
お試しください。

This entry was posted on 木曜日, 1月 31st, 2013 at 11:34 AM and is filed under Python. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

Unityによるゲームを公開しております iOS/Android
https://itunes.apple.com/jp/app/lost-knight-3d-action/id900917032
https://play.google.com/store/apps/details?id=com.groundroad.runknight

各種開発支援・機能開発等小さいお仕事などもお請けしております。
unity開発支援, PHPシステム開発, javascript/html5 フロント開発, titanium mobileアプリ開発
お気軽にお問い合わせください
大崎・五反田近郊での対面でのお打ち合わせはいつでも可能です。