Using Python to convert and image to string?

An external application written in C ++ requires me to pass an image object that it understands, that is, using the tostring () method, passing in the encoder and parameters.

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

image_url is the url of the actual image online ie http://www.test.com/image1.jpg

Here's what I've 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 also tried to open the image to convert it

image = Image.open(image_url)

      

but get error

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

+3


source to share


1 answer


I think you can get an online image using requests.get

.

The code will look like this:



def pass_image(image_url):

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

      

+2


source







All Articles