2009-09-08 13 views

答えて

31

:あなたはこの画像データが有効でない場合でも、画像であることを確認したい場合は

import urllib2 
img = urllib2.urlopen("http://example.com/image.jpg").read() 

を確認するには、PIL

import StringIO 
from PIL import Image 
try: 
    im = Image.open(StringIO.StringIO(img)) 
    im.verify() 
except Exception, e: 
    # The image is not valid 

を使用することができます。あなたは使用できますimghdr

import imghdr 
imghdr.what('ignore', img) 

このメソッドはヘッダーをチェックし、イメージの種類を決定します。イメージが識別できない場合、Noneを返します。

5

ダウンロードのもの

import urllib 
url = "http://example.com/image.jpg" 
fname = "image.jpg" 
urllib.urlretrieve(url, fname) 

それは多くの方法で行うことができる画像であることを確認します。一番難しいのは、Python Image Libraryでファイルを開き、エラーが発生したかどうかを確認することです。

ダウンロードする前にファイルの種類を確認する場合は、リモートサーバーが提供するMIMEタイプを確認してください。ダウンロードするには

import urllib 
url = "http://example.com/image.jpg" 
fname = "image.jpg" 
opener = urllib.urlopen(url) 
if opener.headers.maintype == 'image': 
    # you get the idea 
    open(fname, 'wb').write(opener.read()) 
2

同じことコピー遠隔画像に対する質問の一部についてはhttplib2 ...

from PIL import Image 
from StringIO import StringIO 
from httplib2 import Http 

# retrieve image 
http = Http() 
request, content = http.request('http://www.server.com/path/to/image.jpg') 
im = Image.open(StringIO(content)) 

# is it valid? 
try: 
    im.verify() 
except Exception: 
    pass # not valid 
0

を使用して、ここでthis answerに触発された答えがあります:

import urllib2 
import shutil 

url = 'http://dummyimage.com/100' # returns a dynamically generated PNG 
local_file_name = 'dummy100x100.png' 

remote_file = urllib2.urlopen(url) 
with open(local_file_name, 'wb') as local_file: 
    shutil.copyfileobj(remote_file, local_file) 

。なお、このアプローチは、任意のバイナリメディアタイプのリモートファイルをコピーするために機能します。

関連する問題