python 如何在python中复制远程图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1394721/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I copy a remote image in python?
提问by Nadia Alramli
I need to copy a remote image (for example http://example.com/image.jpg
) to my server. Is this possible?
我需要将远程图像(例如http://example.com/image.jpg
)复制到我的服务器。这可能吗?
How do you verify that this is indeed an image?
你如何验证这确实是一个图像?
回答by Nadia Alramli
To download:
去下载:
import urllib2
img = urllib2.urlopen("http://example.com/image.jpg").read()
To verify can use PIL
验证可以使用PIL
import StringIO
from PIL import Image
try:
im = Image.open(StringIO.StringIO(img))
im.verify()
except Exception, e:
# The image is not valid
If you just want to verify this is an image even if the image data is not valid:You can use imghdr
如果即使图像数据无效,您也只是想验证这是一个图像:您可以使用imghdr
import imghdr
imghdr.what('ignore', img)
The method checks the headers and determines the image type. It will return None if the image was not identifiable.
该方法检查标题并确定图像类型。如果图像无法识别,它将返回 None 。
回答by Jochen Ritzel
Downloading stuff
下载东西
import urllib
url = "http://example.com/image.jpg"
fname = "image.jpg"
urllib.urlretrieve( url, fname )
Verifying that it is a image can be done in many ways. The hardest check is opening the file with the Python Image Library and see if it throws an error.
可以通过多种方式验证它是一个图像。最难的检查是使用 Python 图像库打开文件并查看它是否会引发错误。
If you want to check the file type before downloading, look at the mime-type the remote server gives.
如果您想在下载前检查文件类型,请查看远程服务器提供的 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() )
回答by Luke Sneeringer
Same thing using httplib2...
同样的事情使用 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
回答by DavidRR
For the portion of the question with respect to copyinga remote image, here's an answer inspired by 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)
Note that this approach will work for copying a remote file of any binary media type.
请注意,此方法适用于复制任何二进制媒体类型的远程文件。