使用Python将图像转换为字符串?

3

一个用C++编写的外部应用程序要求我传入一张图片对象,它需要使用tostring()方法并传递编码器和参数。

我该如何获取图片并将其转换为字符串(而不保存图像到文件)?

image_url是在线实际图像的URL,例如:http://www.test.com/image1.jpg

这是我尝试过的:

def pass_image(image_url):

    import base64
    str = base64.b64encode(image_url.read())


    app = subprocess.Popen("externalApp",
                            in=subprocess.PIPE,
                            out=subprocess.PIPE)
    app.in.write(str)
    app.in.close()

我尝试打开该图片并对其进行转换。
image = Image.open(image_url)

但是出现了错误

file()的第一个参数必须是不含有空字节的编码字符串,而不是str类型。

1个回答

2

我认为您可以使用requests.get获取在线图像。

您的代码将会是这样的:

def pass_image(image_url):

    import base64
    import requests
    str = base64.b64encode(requests.get(image_url).content)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接