以下是用 Python 实现本地图片缓存的代码示例,可以帮助您提高代码效率并减少网络请求:

import requests
import os

# 设置图片缓存目录
cache_dir = './image_cache'
if not os.path.exists(cache_dir):
    os.mkdir(cache_dir)

def download_image(url):
    # 从缓存中查找图片
    filename = os.path.join(cache_dir, url.split('/')[-1])
    if os.path.exists(filename):
        print(f'Using cached image {filename}')
        return filename

    # 缓存中没有该图片,则下载图片
    response = requests.get(url)
    if response.status_code == 200:
        with open(filename, 'wb') as f:
            f.write(response.content)
        print(f'Downloaded image {filename}')
        return filename
    else:
        print('Failed to download image')
        return None

# 测试代码
url = 'https://picsum.photos/200/300'
filename = download_image(url)
if filename:
    print(f'Image saved to {filename}')
    # 在此处插入显示图片的代码
else:
    print('Failed to download image')

这段代码使用 cache_dir 变量来指定图片缓存目录。下载图片时,它会先检查缓存目录中是否存在该图片。如果存在,则直接返回缓存文件的路径;否则,下载图片并将其保存到缓存目录中,然后返回文件路径。

缓存的优势在于,如果再次下载相同 URL 的图片,可以直接从本地缓存读取,无需再次从网络上下载。这样可以提高代码效率,减少网络请求次数。

Python 图片缓存:提高效率,减少网络请求

原文地址: https://www.cveoy.top/t/topic/nVyB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录