How to save an image on the internet to local file in Python

I want to take direct image links from reddit and imgur, save them to file, and then upload them to twitter. There is no real reason I’m doing this, I just want the practice as I am new to programming. I am unsure on how to save an image link to file though. I came across a StackOverflow question that asked this same thing, and the answer that person was given was to use urllib.retrieve.

This is the code that I am using:

def post_to_twitter():
    if 'i.redd.it/' in submission.url or 'i.imgur.com/' in submission.url:
        print(submission.url)
        urllib.urlretrieve(str(submission.url),'<my directory>')
    elif 'i.redd.it/' not in submission.url or 'i.imgur.com/' not in submission.url:
        print('No direct imgur or reddit image link')

However, when I run this code, I get a unicode error that I have never come across before – (unicode error) ‘unicodeescape’ codec can’t decode bytes in position 2-3: truncated /UXXXXXXXX escape and then IDLE highlights the comma that I used between the submission URL and my chosen directory.

Obviously this is the wrong code, I am sure that saving to file using an image link is not as easy as using a single line of code. What is it that I’m doing wrong, or is there just a better way to do this? If possible, could you please explain like I’m five. I’m new to programming and don’t understand some words yet which get me confused.


I found the solution.

I actually managed to get this working with the original code I used, but slightly tweaked.

I used:

urllib.request.urlretrieve(submission.url, 'Reddit To Twitter Downloaded Images//'+submission.id+'.jpeg')

submission.url returns the link to the image, so you can replace that with whatever you want, as long as it is equal to the direct image link as a string, such as my_url = “http://i.imgur.com/qjMiF2A.gif”

‘Reddit To Twitter Downloaded Images//’+submission.id+’.jpeg’ is the name of the image you want to save. You can also specify the path in it. However, because I can’t manually specify what I want the file to save as, I use the submission.id as the file name, so that way I can guarantee it will always be unique. I then just add .jpeg at the end of it to specify the file type.

try this:

import os
import urllib.request
import urllib.error
def saveImg(url,path,name):
    #url is imgurl 
    #path is your folder 
    #name is like tmp.png
    if not os.path.exists(path):
        os.mkdir(path)
    try:
        response=urllib.request.urlopen(url);
    except urllib.error.URLError as e:
        return 0
    except urllib.error.HTTPError as e:
        return 0
    code=response.read()
    filehandle=open(path+name,'wb');
    filehandle.write(code)
    filehandle.close()
    return 1

You need to pip PIL and Requests first
The cleanest way is

from PIL import Image
import requests
from io import BytesIO
r=requests.get(name)
image=Image.open(BytesIO(r.content))
image.save('{0}.jpg'.format("Image"))

I actually managed to get this working with the original code I used, but slightly tweaked.

I used:

urllib.request.urlretrieve(submission.url, 'Reddit To Twitter Downloaded Images//'+submission.id+'.jpeg')

submission.url returns the link to the image, so you can replace that with whatever you want, as long as it is equal to the direct image link as a string.

‘Reddit To Twitter Downloaded Images//’+submission.id+’.jpeg’ is the name of the image you want to save. You can also specify the path in it. However, because I can’t manually specify what I want the file to save as, I use the submission.id as the file name, so that way I can guarantee it will always be unique. I then just add .jpeg at the end of it to specify the file type.