Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Python to convert and image in to a string?

Tags:

python

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.

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

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

like image 828
Prometheus Avatar asked May 17 '26 07:05

Prometheus


1 Answers

I think you can get a online image by using 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)
like image 71
WKPlus Avatar answered May 19 '26 22:05

WKPlus