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( )
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) :
response = requests. get( image_url)
if response. status_code == 200 :
image_data = BytesIO( response. content)
image = PILImage. open ( image_data)
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( )
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) :
response = requests. get( image_url)
if response. status_code == 200 :
image_data = BytesIO( response. content)
image = PILImage. open ( image_data)
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( )