从网络上下载的图片

我这边有个需求,是在web编辑博客的时候插入图片不方便,遂写了一个python脚本用于下载网络图片并存在指定路径下.支持不同的图片格式,有需求可以直接用下面的脚本经行修改.
之前的流程是先找到图片在web提交到指定路径,然后再进行插入现在就只需要复制控制台输出的标签即可.

运行环境

需要python3.x
需要pip 安装 requests

测试指令

参数可以加两位,第一位是地址,第二位是图片格式默认是png

1
2
[root@iZky7h4oconc7uZ workingcopy_blog]# python3 download_img.py 'https://icxzl.com/wp-content/uploads/2023/03/centos-7-upgrades-python-3.12.png' 
Image downloaded and saved as ![](../uploads/2024-04-23-17-57-00.png) in /www/wwwroot/workingcopy_blog/source/uploads

现在只需要复制地址标签即可.

完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# -*- coding: utf-8 -*- 
import requests
import os
from datetime import datetime
import sys

def download_and_save_image(url, directory,image_formate):
# 获取当前日期和时间,用于命名文件
now = datetime.now()
filename = now.strftime("%Y-%m-%d-%H-%M-%S.") + image_formate
filepath = os.path.join(directory, filename)

try:
# 发送GET请求获取图片
response = requests.get(url, stream=True)
response.raise_for_status() # 如果请求失败则抛出异常

# 打开文件以二进制写入模式
with open(filepath, 'wb') as file:
# 将响应内容写入文件
for chunk in response.iter_content(chunk_size=8192):
file.write(chunk)

print(f"Image downloaded and saved as {filename} in {directory}")

except requests.RequestException as e:
print(f"Error occurred while downloading image: {e}")

if __name__ == "__main__":
# 检查命令行参数数量
if len(sys.argv) < 2 or len(sys.argv) > 3:
print("Usage: python script_name.py <image_url> [directory_path]")
print("If [directory_path] is not provided, the current script directory will be used.")
sys.exit(1)

# 获取URL参数
url = sys.argv[1]
directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), "source", "uploads")

image_formate = "png"
# 获取目录参数,如果没有提供则使用当前脚本所在目录
if len(sys.argv) == 3:
image_formate = sys.argv[2]

# 检查目录是否存在,如果不存在则创建
if not os.path.exists(directory):
os.makedirs(directory)

# 下载并保存图片
download_and_save_image(url, directory,image_formate)