使用Python转换并成像为字符串?

时间:2022-01-18 08:57:00

An external application written in c++ requires me to pass in an image object it would understand i.e. with tostring() method, passing in a encoder and parameters.

用c ++编写的外部应用程序要求我传入一个它能理解的图像对象,即使用tostring()方法,传入一个编码器和参数。

How can I get the image and convert it to a string (without saving the image to file)?

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

image_url is the url to an actual image online i.e http://www.test.com/image1.jpg

image_url是在线实际图像的网址,即http://www.test.com/image1.jpg

This is what I have tried:

这是我尝试过的:

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

I have also tried to open the image to convert it

我也尝试打开图像进行转换

image = Image.open(image_url)

but get the error

但得到错误

file() argument 1 must be encoded string without NULL bytes, not str

file()参数1必须是没有NULL字节的编码字符串,而不是str

1 个解决方案

#1


2  

I think you can get a online image by using requests.get.

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

You code will be like this:

你的代码将是这样的:

def pass_image(image_url):

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

#1


2  

I think you can get a online image by using requests.get.

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

You code will be like this:

你的代码将是这样的:

def pass_image(image_url):

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