在python请求中下载图像的推荐方法

2024-10-03 04:26:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我发现有两种方法可以使用python reuqests下载图像

  1. 使用文件(https://requests.readthedocs.io/en/master/user/quickstart/#binary-response-content)中所述的PIL:

    from PIL import Image
    from io import BytesIO
    i = Image.open(BytesIO(r.content))
    
  2. 使用流式响应内容:

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

但是,建议wya下载哪些图像?这两种方法都有其优点,我想知道什么是最佳方法


Tags: 文件方法fromhttpsio图像imageimport
2条回答

我确实在一个函数中使用了下面几行代码来保存图像

    # 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

我喜欢极简主义的方式。没有所谓的正确方法。这取决于您想要执行的任务和约束条件


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

相关问题 更多 >