2

I see that there are two ways to download images using python-reuqests.

  1. Uisng PIL as stated in docs (https://requests.readthedocs.io/en/master/user/quickstart/#binary-response-content):

    from PIL import Image
    from io import BytesIO
    i = Image.open(BytesIO(r.content))
    
  2. using streamed response content:

    r = requests.get(url, stream=True)
    with open(image_name, 'wb') as f:
        for chunk in r.iter_content():
            f.write(chunk)
    

Which is the recommended wya to download images however? both have its merits I suyppose, and I was wondering what is the optimal approach.

8
  • what is r.content in the first option?
    – balderman
    Sep 20, 2020 at 10:38
  • @balderman I presume this is requests.content Sep 20, 2020 at 10:52
  • @AndrejKesely I think so as well.. so what is the point to use PIL and requests if all you want to do is to save image to the disk?
    – balderman
    Sep 20, 2020 at 10:55
  • 1
    @balderman If you want to save just to disk, there's no point to go through PIL, just f.write() it to disk. Like an answer below. Sep 20, 2020 at 10:58
  • 1
    @AJW Yes - I missed the NO ...
    – balderman
    Sep 20, 2020 at 11:07

2 Answers 2

14

I love the minimalist way. There is nothing called right way. It depends on the task you want to perform and the constraints you have.


import requests

with open('file.png', 'wb') as f:
    f.write(requests.get(url).content)
# if you change png to jpg, there will be no error
0

I did use the below lines of code in a function to save images.

    # import the required libraries from Python
    import pathlib,urllib.request,os,uuid
    
    # URL of the image you want to download
    image_url = "https://example.com/image.png"

    # Using the uuid generate new and unique names for your images
    filename = str(uuid.uuid4())

    # Strip the image extension from it's original name
    file_ext = pathlib.Path(image_url).suffix
    
    # Join the new image name to the extension
    picture_filename = filename + file_ext

    # Using pathlib, specify where the image is to be saved
    downloads_path = str(pathlib.Path.home() / "Downloads")

    # Form a full image path by joining the path to the 
    # images' new name
    picture_path  = os.path.join(downloads_path, picture_filename)

    # Using "urlretrieve()" from urllib.request save the image
    urllib.request.urlretrieve(image_url, picture_path)

    # urlretrieve() takes in 2 arguments
    # 1. The URL of the image to be downloaded
    # 2. The image new name after download. By default, the image is 
    #    saved inside your current working directory

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.