ほんじゃらねっと

ダイエット中プログラマのブログ

DjangoとPILで画像のフォーマットを取得

画像を外部URLから取得する際に画像フォーマットが分からない場合、下記の方法で取得できた。

Python Imaging LibraryとDjangoを使った方法。

import urllib
from PIL import Image
from django.core.files.base import ContentFile
image_url = "画像ファイルのURL"
f = urllib.urlopen(image_url)
# これで取得できるかと思ったけど、「application/octet-strem」とかだと分からない
## file_info = f.info()
## print file_info.gettype()
image_content = ContentFile(f.read()) # StringIOとかでもいける?
im = Image.open(image_content)
image_format = im.format.lower()
print image_format # これでjpegとかpngとか分かる