Search code examples
pythongoogle-cloud-vision

How to read bytes from a image url (jpeg) and encode in base64 on Python 2.7?


I am using the following code:

import urllib, cStringIO
from PIL import Image  
url='https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png'
file = cStringIO.StringIO(urllib.urlopen(url).read())
img = Image.open(file)

based on: How do I read image data from a URL in Python?

Now I need to base64 encode it for posting to Google Cloud Vision API. How to do that?

Or does the Google Cloud vision API work with image urls?


Solution

  • Assuming there's no need to parse the image, just grab it and encode it:

    import urllib2
    import base64
    url = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png'
    contents = urllib2.urlopen(url).read()
    data = base64.b64encode(contents)
    print data