[Python] Downloading image with PIL and requests

Discussão em 'Python' iniciado por Stack, Março 30, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to download an original image (png format) by url, convert it on the fly (without saving to disc) and save as jpg.

    The code is following:

    import os
    import io
    import requests
    from PIL import Image
    ...
    r = requests.get(img_url, stream=True)
    if r.status_code == 200:
    i = Image.open(io.BytesIO(r.content))
    i.save(os.path.join(out_dir, 'image.jpg'), quality=85)


    It works, but when I try to monitor the download progress (for the future progress bar) with r.iter_content() like this:

    r = requests.get(img_url, stream=True)
    if r.status_code == 200:
    for chunk in r.iter_content():
    print(len(chunk))
    i = Image.open(io.BytesIO(r.content))
    i.save(os.path.join(out_dir, 'image.jpg'), quality=85)


    I get this error:

    Traceback (most recent call last):
    File "E:/GitHub/geoportal/quicklookScrape/temp.py", line 37, in <module>
    i = Image.open(io.BytesIO(r.content))
    File "C:\Python35\lib\site-packages\requests\models.py", line 736, in content
    'The content for this response was already consumed')
    RuntimeError: The content for this response was already consumed


    So is it possible to monitor the download progress and after get the data itself?

    Continue reading...

Compartilhe esta Página