python直接下载图片到内存

本文介绍了如何利用Python中的requests库结合PIL库来下载图片,并展示了不同方式打开及读取图片的方法。此外,还提供了一个批量下载验证码图片的多进程示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 使用requests(推荐)

from PIL import Image
import requests
Image.open(requests.get(url, stream=True).raw)

  1. 使用StringIO

复制代码
from PIL import Image
from StringIO import StringIO
import requests

r = requests.get(“http://a/b/c”)
im = Image.open(StringIO(r.content))
im.size

=======================

from PIL import Image
import urllib2 as urllib
from StringIO import StringIO

fd = urllib.urlopen(“http://a/b/c”)
im = Image.open(StringIO(fd.read()))
im.size

复制代码

  1. 使用io.BytesIO

复制代码
from PIL import Image
import urllib2 as urllib
import io

fd = urllib.urlopen(“http://a/b/c”)
image_file = io.BytesIO(fd.read())
im = Image.open(image_file)
复制代码

复制代码
#!/usr/bin/env python

coding=utf-8

from urllib2 import urlopen
import random
import time

from multiprocessing import Pool

url_root = ‘http://www.beianbeian.com/gaoji/validate_code?a=
cnt = 1000

def download_img(url, path=‘static/uploads/’):
global cnt
while cnt < 2000:
fname = path + “BA%d.jpg” % cnt
with open(fname, ‘wb’) as fw:
try:
fw.write(urlopen(url).read())
print fname, ‘done’
cnt += 1
except Exception as e:
print ‘Error’, e
continue

    time.sleep(0.2)

if name == “main”:

pool = Pool(processes=4)
for i in range(10):
    randNum = random.random()
    url = url_root + str(randNum)
    pool.apply(download_img, args=(url,))
    pool.close()
    pool.join()
### 如何使用Python实现图片下载 #### 准备工作 为了能够顺利地利用Python完成图片下载的任务,需要先安装`requests`库用于发起HTTP请求获取网络资源以及`PIL`(来自Pillow包)来处理图像文件。可以通过pip命令轻松安装这两个依赖项。 ```bash pip install requests pillow ``` #### 获取图片URL 要下载一张图片,首先要有一个有效的图片链接地址作为目标源。此链接应当指向可以直接访问到的图片资源而不是网页中的HTML文档或者其他形式的内容[^3]。 #### 发起HTTP GET请求 通过`requests.get()`函数向服务器发送GET请求以获得响应对象,其中包含了所请求页面的数据流。对于图片这类二进制数据来说,应该关注于读取其`.content`属性而非`.text`。 #### 处理异常情况 考虑到网络状况不稳定等因素,在实际编码过程中加入try-except结构用来捕获可能出现的各种错误是非常必要的做法之一。比如连接失败、超时等问题都可以在此处得到妥善解决。 #### 存储图片至本地 最后一步就是把接收到的数据保存成指定格式的文件了。这里推荐采用with语句打开文件的方式操作,这样可以在不显式调用close()的情况下自动关闭文件描述符,减少内存泄漏的风险。 下面是完整的代码示例: ```python import os import requests from PIL import Image from io import BytesIO def download_image(url, path): try: response = requests.get(url, stream=True) response.raise_for_status() with open(path, 'wb') as out_file: for chunk in response.iter_content(1024): if not chunk: break out_file.write(chunk) del response # Verify that the file is an image and it's valid. img = Image.open(path) img.verify() print(f'Successfully downloaded {url} to {path}') except Exception as e: print(f'Failed to download {url}:', str(e)) if __name__ == '__main__': url = "https://example.com/image.jpg" filename = "./downloaded_image.jpg" directory = os.path.dirname(filename) if not os.path.exists(directory): os.makedirs(directory) download_image(url=url, path=filename) ``` 这段代码实现了从给定网址下载图片并将其存储在当前目录下的功能。如果指定了子文件夹,则会检查该文件夹是否存在;不存在的话则创建它[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值