在python 3中从http打开图像 [英] Opening image from http in python 3

查看:127
本文介绍了在python 3中从http打开图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道现在有上千个这样的问题,但是所提供的解决方案都没有真正起作用. 我正在使用pythong 3.4. 我想直接将URL作为图像打开,而不是先将其存储在磁盘上.

I know there are a thousand questions like that out there but none of the provided solutions do actually work. I am using pythong 3.4. I would like to directly open the url as an image, not store it first on the disk.

基本上,代码归结于此

from PIL import Image <br />
import urllib.request <br />
... <br />
opener = urllib.request.build_opener() <br />
file = opener.open("http://pixel.quantserve.com/pixel") <br />
img = Image.open(file.read()) <br />
width, height = img.size


这给我带来了一个错误.我也尝试了没有 .读() 和
文件= urllib.request.urlopen("...")
有和没有.read()

This yields for me an error. I also tried it without the .read() and with
file = urllib.request.urlopen("...")
both with and without the .read()

基本上我迷路了.我唯一能做的就是更改python向我抛出的错误.谢谢你的帮助!
带有上述版本的错误消息:
TypeError:嵌入的NUL字符
没有read()
io.UnsupportedOperation:查找

使用不带.read()的"urllib.request.urlopen(" ...)
io.UnsupportedOperation:查找

与.read()
TypeError:嵌入的NUL字符

Basically I am lost. The only thing I can do is change the error that python is throwing at me. Thanks for any help!
Error messages with the above mentioned version:
TypeError: embedded NUL character
Without the read()
io.UnsupportedOperation: seek

With "urllib.request.urlopen("...") without .read()
io.UnsupportedOperation: seek

with .read()
TypeError: embedded NUL character

推荐答案

为避免使用tkinter并避免在本地写入文件,请使用缓冲区:

To avoid using tkinter and to avoid writing the file locally, use a buffer:

from PIL import Image
import urllib
from io import BytesIO

f = urllib.urlopen("http://pixel.quantserve.com/pixel")
b = BytesIO(f.read())
i = Image.open(b)

i # <PIL.TgaImagePlugin.TgaImageFile image mode=P size=512x17410 at 0x7FBA4A3712D8>

这使用的是2.7,但没有urllib.request,因此请根据需要进行修改.

This is using 2.7, which doesn't have urllib.request, so modify this as required.

另外,请注意,此图片似乎格式不正确/无效

Also, be aware that this image appears to be malformed/invalid

这篇关于在python 3中从http打开图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆