3

I'm currently developing a small script to take screenshots and upload them to imgur using Python.

The code looks like this:

import time
import os
import ImageGrab
import urllib
import urllib2

time.sleep(1)
shot = ImageGrab.grab()
dir = os.path.join(r'C:\SAMPLE\PATH', 'Screen ' + time.strftime(r'%Y-%m-%d %H-%M-%S') + '.png')
shot.save(dir)

data = urllib.urlencode({"key":'MY_API_KEY', "image":urllib.quote(open(dir,'rb').read().encode("base64"))})

site = urllib2.Request("http://imgur.com/api/upload.json", data)
s = urllib2.urlopen(site)

print s.read()

I get a response from imgur but when I open the link I get a blank image (though its resolution is correct). I think the base64 encoding method may be off but I'm at a loss.

Fernando Martin
  • 512
  • 1
  • 6
  • 21
  • Are you sure the screengrab has been saved to the file you've read? Try it with another image with the name hardcoded. – agf Jul 31 '11 at 03:20
  • @agf Yes, the file *is* there and I tried with a hardcoded path to another image with no avail. Thanks though. – Fernando Martin Jul 31 '11 at 03:27

1 Answers1

0

You should use b64encode from the base64 module. I don't know why, but it gives different results:

from base64 import b64encode

(...)

data = urllib.urlencode({"key":'MY_API_KEY', "image":urllib.quote(b64encode(open(dir,'rb').read()))})
nmat
  • 7,430
  • 6
  • 30
  • 43
  • Still getting the same result. – Fernando Martin Jul 31 '11 at 05:25
  • I don't know what's wrong then... I searched for a few examples of python and imgur's JSON API and your code seems correct: http://garciat.info/easy-python-imgur-uploader http://pastebin.com/NiaJbhhP – nmat Jul 31 '11 at 05:36
  • @FernandoMartin If the answer worked out for you, you should `accept` it, since it gives some points to the one who took the time to write out the answer – TankorSmash Jun 01 '12 at 14:29
  • @TankorSmash: I know, but the answer didn't work for me; the comment did, and it was by a different author. – Fernando Martin Jun 02 '12 at 05:28
  • @FernandoMartin Oh, good point. You'd still think though that his basic idea was the same though. In the end it's up to you. Off topic though, have you seen the `requests` module? Makes this stuff a ton easier. – TankorSmash Jun 02 '12 at 13:47