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

17 投票
4 回答
15413 浏览
提问于 2025-04-15 14:09

我想把一个远程的图片(比如 http://example.com/image.jpg)复制到我的服务器上。这可能吗?

你怎么确认这确实是一个图片呢?

4 个回答

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
5

下载东西

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

验证一个文件是否是图片有很多种方法。最难的检查方式是用Python的图像库打开这个文件,看看会不会报错。

如果你想在下载之前检查文件类型,可以查看远程服务器提供的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() )
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。

撰写回答