【问题标题】:Opening image from http in python 3在python 3中从http打开图像
【发布时间】:2015-02-07 14:37:47
【问题描述】:

我知道有上千个这样的问题,但所提供的解决方案都没有真正奏效。 我正在使用 pythong 3.4。 我想直接把url作为图片打开,而不是先存到磁盘上。

基本上代码归结为这个

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()

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

使用 "urllib.request.urlopen("...") 没有 .read()
io.UnsupportedOperation: 寻找

使用 .read()
类型错误:嵌入 NUL 字符

【问题讨论】:

  • 首先,正确格式化你的代码,python向你抛出的错误是什么?
  • 在问题中添加了错误

标签: python http image-processing


【解决方案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,所以根据需要修改。

另外,请注意此图片格式错误/无效

【讨论】:

  • @notsoimportant 最好的表达方式是将答案标记为正确!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-11
  • 1970-01-01
  • 2019-06-30
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
相关资源
最近更新 更多