Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中复制远程映像?_Python_Download_File Copying - Fatal编程技术网

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

如何在python中复制远程映像?,python,download,file-copying,Python,Download,File Copying,例如,我需要复制远程映像http://example.com/image.jpg 到我的服务器。这可能吗 如何确认这确实是一幅图像?正在下载资料 import urllib url = "http://example.com/image.jpg" fname = "image.jpg" urllib.urlretrieve( url, fname ) 可以通过多种方式验证它是否为图像。最难的检查是使用Python图像库打开文件,看看它是否抛出错误 如果要在下载之前检查文件类型,请查看远程服务器

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

如何确认这确实是一幅图像?

正在下载资料

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() )
下载:

import urllib2
img = urllib2.urlopen("http://example.com/image.jpg").read()
要验证是否可以使用

如果您只是想验证这是一个图像,即使图像数据无效:您可以使用


该方法检查标题并确定图像类型。如果图像不可识别,它将返回None。

使用httplib2时也会返回None

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

对于问题中有关复制远程图像的部分,以下是一个受以下启发的答案:

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

import imghdr
imghdr.what('ignore', img)
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
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)