封装 Python 常用函数
将网络图片保存到临时文件中
import requests
import tempfile
import os
def save_image_from_url(url):
try:
response = requests.get(url)
response.raise_for_status() # 检查HTTP请求是否成功
if 'image' in response.headers['content-type']:
# 创建临时文件
with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as temp_file:
temp_file.write(response.content)
temp_file.close()
return temp_file.name
else:
print("URL不是图片")
return None
except requests.exceptions.RequestException as e:
print(f"下载图片时出错: {e}")
return None