基于图像链接的批量下载

1. 获取图像路径

1.1 给定图像链接,这是一张图像

image_url = “https://univs-news-1256833609.cos.ap-beijing.myqcloud.com/123/upload/resources/image/7467914.jpg”

1.1通过网站规则得到其想要的图像链接

image_urls = [
f"https://univs-news-1256833609.cos.ap-beijing.myqcloud.com/123/upload/resources/image/{7467914 + i*2}.jpg" for i in range(50)
]

1.2 获取传入的参数,如果传入的图像路径参数是空,则判断是否使用默认的配置(非指定想要的图像链接)

if opt.image_urls:
    image_urls = opt.image_urls
else:
    while True:
        input_id = int(input("The following options:\n [0]: stop running. \n [1]: use default config.\nPlease enter the correct option: "))

        if input_id == 0:
            sys.exit()  # 退出程序
            # break
        elif input_id == 1:
            image_urls = [
                f"https://univs-news-1256833609.cos.ap-beijing.myqcloud.com/123/upload/resources/image/{7467914 + i * 2}.jpg"
                for i in range(50)
            ]
            break  # 输入正确,跳出循环
        else:
            print("input number is wrong,please input correct.\n")

2. 通过图像路径,获取图像,并下载到本地

# 遍历下载图像
    id = 1
    for i, image_url in enumerate(image_urls):
        # 发起HTTP请求获取图像数据
        response = requests.get(image_url)
        if response.status_code == 200:
            # 将图像数据转换为PIL Image对象
            image_data = BytesIO(response.content)
            image = PILImage.open(image_data)
            # 可以将 image 用于展示、保存或进一步处理
            image.save(f"./{cache_path}/{id}_{image_url.rsplit('/', 1)[1][:-4]}.png")  # 保存图像
            id += 1
        else:
            # 请求不到的数据进行错误返回
            print(f"Failed to download image: {i}_{image_url}")

3. 完整的代码

import os
import shutil
import sys
import argparse
import requests
from PIL import Image as PILImage
from io import BytesIO


def get_opt():
    """参数设置"""
    parse = argparse.ArgumentParser()
    parse.add_argument("--cache_path", type=str, default="./tmp/data", help="缓存文件路径")
    parse.add_argument("--image_urls", type=list, default=[], help="请求的图像链接")
    opt = parse.parse_args()
    return opt


def main():
    # 获取配置信息
    opt = get_opt()
    # 本地缓存路径
    cache_path = opt.cache_path

    # 清除现有的缓存文件夹(如果有的话)
    try:
        shutil.rmtree(cache_path)
    except:
        pass
    # 创建缓存文件夹
    os.makedirs(cache_path)

    # 获取图像链接
    if opt.image_urls:
        image_urls = opt.image_urls
    else:
        while True:
            input_id = int(input("The following options:\n [0]: stop running. \n [1]: use default config.\nPlease enter the correct option: "))

            if input_id == 0:
                sys.exit()  # 退出程序
                # break
            elif input_id == 1:
                image_urls = [
                    f"https://univs-news-1256833609.cos.ap-beijing.myqcloud.com/123/upload/resources/image/{7467914 + i * 2}.jpg"
                    for i in range(50)
                ]
                break  # 输入正确,跳出循环
            else:
                print("input number is wrong,please input correct.\n")

    # 遍历下载图像
    id = 1
    for i, image_url in enumerate(image_urls):
        # 发起HTTP请求获取图像数据
        response = requests.get(image_url)
        if response.status_code == 200:
            # 将图像数据转换为PIL Image对象
            image_data = BytesIO(response.content)
            image = PILImage.open(image_data)
            # 可以将 image 用于展示、保存或进一步处理
            image.save(f"./{cache_path}/{id}_{image_url.rsplit('/', 1)[1][:-4]}.png")  # 保存图像
            id += 1
        else:
            # 请求不到的数据进行错误返回
            print(f"Failed to download image: {i}_{image_url}")


if __name__ == '__main__':
    main()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Kungs8

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值