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

时间:2009-09-08 15:40:06

标签: python download file-copying

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

如何确认这确实是一张图片?

4 个答案:

答案 0 :(得分: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。

答案 1 :(得分: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 :(得分: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

答案 3 :(得分: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)

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