2015-02-07 65 views
0

我知道那裏有上千個問題,但是沒有一個提供的解決方案確實有效。 我正在使用pythong 3.4。 我想直接打開網址作爲圖像,而不是先將它存儲在磁盤上。在python中打開http的圖像3

基本上代碼歸結到這一點

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 


這產生了我一個錯誤。我也有和無.read()

基本上我失去了嘗試它沒有 .read() 與
文件= urllib.request.urlopen( 「...」)
。我唯一能做的就是改變python向我拋出的錯誤。謝謝你的幫助!
錯誤信息與上面提到的版本:
類型錯誤:嵌入式NULL字符
沒有閱讀()
io.UnsupportedOperation:尋求

隨着 「urllib.request.urlopen(」 ...「)沒有。閱讀()
io.UnsupportedOperation:尋求

與.read()
類型錯誤:嵌入式NULL字符

+0

首先,正確格式的代碼,什麼是錯誤的Python拋出你嗎? – 2015-02-07 14:38:36

+0

在問題中增加了錯誤 – notsoimportant 2015-02-07 15:25:21

回答

1

爲了避免使用Tkinter的,避免書寫該文件在本地,使用緩衝區:

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,從而需要進行修改。

此外,要知道,這種圖像格式似乎不正確/無效

+0

BytesIO節省了一天:)謝謝soooo太多 – notsoimportant 2015-02-07 17:35:50

+0

@notsoimportant說這個最好的方法是將答案標記爲正確! – Paul 2015-02-07 20:39:42