首页 > 解决方案 > 让Python从URL打开一张图片

问题描述

我做了这个项目,你训练机器学习来回应你对它说的话。

这是我得到的 Python 代码:

from PIL import Image
import requests
 
def classify(text):
    key = "#my credits activation key"
    url = "https://machinelearningforkids.co.uk/api/scratch/"+ key + "/classify"
 
    response = requests.get(url, params={ "data" : text })
 
    if response.ok:
        responseData = response.json()
        topMatch = responseData[0]
        return topMatch
    else:
        response.raise_for_status()
 
input = input("What do you want to tell me? > ")
 
recognized = classify(input)
 
label = recognized["class_name"]
 
if label == "kind_things":
    print ("Mmm, thanks")
    img = Image.open("happy.png")
    img.show()
else:
    print ("Well screw you too!")
    img = Image.open("sad.png")
    img.show()

这样它就可以工作,所以我假设我已经正确安装了所有东西(pip、Pillow 等)。

现在,我想更进一步,用它制作一个可执行文件(使用 PyInstaller,我做了),然后把它作为一个笑话发送给我的朋友。这个想法是,如果他们写了一些好东西,他们会得到很好的回应,并且从 URL 中打开一张我微笑的照片。如果他们说刻薄的话,那么他们会得到刻薄的回应,我的愤怒画面就会打开。

这就是我到目前为止所尝试的:

if label == "kind_things":
    print ("Mmm, thanks")
    url = "#url of the picture"
    response = requests.get(url)
    img = Image.open(response.raw)
    img.show()
else:
    print ("Well screw you too!")
    url = "#url of the other picture"
    response = requests.get(url)
    img = Image.open(response.raw)
    img.show()

它不起作用。我在python中遇到的错误:

PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x0000023B5072C180>

我读到了urllibor bytesIOor之类的东西StringIO,但不确定在这种情况下如何使用它们中的任何一个。

标签: pythonpython-requestspython-imaging-library

解决方案


如果您需要在网络上远程访问图像,这应该可以:

from io import BytesIO

import requests
from PIL import Image

response = requests.get('http://the/url')
img = Image.open(BytesIO(response.content))
img.show()

也就是说,将图像与可执行文件一起包含可能更有意义。您可以使用该--onefile选项将它们打包到 .exe 文件中,而不是将它们放在一个文件夹中,以稍微掩盖工作原理。(我想如果你的朋友在你给他们程序的时候看到图像,你会失去一些有趣的惊喜效果。)


推荐阅读