如何在Python中复制远程图像?

17

我需要将远程图片(例如http://example.com/image.jpg)复制到我的服务器上。这可行吗?

如何验证这确实是一张图像?

4个回答

33

下载:

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

1

关于复制远程图片的部分问题,这里有一个受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)

请注意,此方法适用于复制任何二进制媒体类型的远程文件。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接