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で以下を実行。
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
とりあえず比率固定ですが、サムネイル生成のようなものが必要なので作る。
こんな感じで
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分かからないと思います。
お試しください。