やってみる

アウトプットすべく己を導くためのブログ。その試行錯誤すらたれ流す。

DB内のフォトライフ画像をディスプレイに表示する

PythonとPillowとImageMagickで。

成果物

GitHubPillow.Load.201703041706

実行結果

f:id:ytyaru:20170304191625g:plain

このブログで最初に投稿した画像を表示した。

開発環境

はてなフォトライフAtomAPI - Hatena Developer Center

なお、使用させていただいたライブラリは以下のライセンスである。感謝。

Library License Copyright
xmltodict MIT Copyright © 2012 Martin Blech and individual contributors.
requests_oauthlib ISC Copyright © 2014 Kenneth Reitz.
bs4 MIT Copyright © 1996-2011 Leonard Richardson,参考
dataset MIT Copyright © 2013, Open Knowledge Foundation, Friedrich Lindenberg, Gregor Aisch
pillow MIT Copyright © 2010-2017 by Alex Clark and contributors
PIL MIT Copyright © 1997-2011 by Secret Labs AB,Copyright © 1995-2011 by Fredrik Lundh
ImageMagick ImageMagick License Copyright © 1999-2017 ImageMagick Studio LLC

前回まで

http://ytyaru.hatenablog.com/entry/2017/07/08/000000
http://ytyaru.hatenablog.com/entry/2017/07/09/000000
http://ytyaru.hatenablog.com/entry/2017/07/10/000000
http://ytyaru.hatenablog.com/entry/2017/07/11/000000

今回

SQLite3のBLOBに保存した画像データをディスプレイに表示する。

gif,png,jpgなどをそのままDBに保存したものを表示する。

使うもの

ソフト 説明
Pillow Pythonの画像処理ライブラリ。PIL(Python Image Library)の後継。
ImageMagick 画像処理ツール。

install

Pillow

$ sudo pip3 install Pillow
Requirement already satisfied (use --upgrade to upgrade): Pillow in /usr/lib/python3/dist-packages
Cleaning up...

ImageMagick

Pythonパッケージではない。Synapticパッケージマネージャでインストールした。

f:id:ytyaru:20170304191533g:plain
f:id:ytyaru:20170304191548g:plain
f:id:ytyaru:20170304191600g:plain

画像の表示ができるらしいPillowを使うことにする。

画像の読込と表示

from PIL import Image
from io import BytesIO
import dataset

image = self.db_photo['Contents'].find_one(ItemId='20160608222919')['Content']
i = Image.open(BytesIO(image))
i.show()

C#でいうMemoryStream的なやつが、StringIO、BytesIOと思われる。バイナリ形式ならBytesIOを使う。Python2と3ではパッケージ名などが違う。上記はPython3。

i.show()ImageMagickの表示ツールを呼び出すらしいので要インストール

調査

読み込み

Requests の使い方 (Python Library) - Qiita

>>> from PIL import Image
>>> from StringIO import StringIO
>>> r = requests.get('http://www.fnal.gov/faw/designstandards/filesfordownload/FermiLogo_blue.gif')
>>> i = Image.open(StringIO(r.content))

python - Convert PILLOW image into StringIO - Stack Overflow

バイナリデータからの読み込み。

Python3 + Bottle + Pillow でレスポンスとして画像を返す - BLOG EX MACHINA

画像の表示

from PIL import Image
im = Image.open("./achan.jpg")
im.show()

Matplotlibで画像を表示 - Qiita

PILはPillowの前身なので同じことがPillowでもできるはず。

python - How can I display an image using Pillow? - Stack Overflow

python - How to show PIL images on the screen? - Stack Overflow

PIL.Image.open().show()ImageMagickdisplayコマンドを呼び出すらしい。というわけで、ImageMagickもインストールする。

参考

参考にした。感謝。

Python、requestsを使ったダウンロード - Pythonメモ torinaブログ
requestsを使った画像のダウンロード - Qiita
Pythonで画像処理 | Nana-Korobi
Pillow(Python Imaging Library)のインストールと簡単なサンプルコード | mwSoft
https://pillow.readthedocs.io/en/4.0.x/

所感

ついにできた。DBから画像が見れたよやったね!