How to base64 encode a picture for twitter in python?

336 views Asked by At

So I have been trying, (without luck) to base64 encode a image to upload to twitter with the Twython library. Iv'e done it the way I know how but it don't seem to work.

from twython import Twython
import base64

#keys
APP_KEY = '*************'
APP_SECRET = '**************'
OAUTH_TOKEN = '**********************'
OAUTH_TOKEN_SECRET = '*************************'
#start twitter instance
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

#encode image to bas64
with open("image.jpeg", "rb") as imageF:
    st = base64.b64encode(imageF.read())
    #print to make sure its being encoded
    print st

#update twitter banner
twitter.update_profile_background_image(image=st)

The twitter docs don't help to much. https://dev.twitter.com/rest/reference/post/account/update_profile_banner Nor does the Twython Docs. https://twython.readthedocs.org/en/latest/api.html Let me know how you would do it. Or if you have a better way.

Thanks

2

There are 2 answers

0
TysonU On BEST ANSWER

Ok, so I thought I would come back and say what I found out. The way I was doing it works. I apparently had made the same call with invalid parameters before and twitter much count all API calls as a call. And they seem to not let you make a banner update call very often. Also I think they expect the image to be the right size, which seems to be(1500px,500px) So you should try to resize the image before you encode it. If someone knows of a simpler way...i'm still open for suggestions.

Thanks for now!

5
sajadkk On

I think it is 'banner' instead of 'image'

twitter.update_profile_background_image(banner=st)