我正在尝试通过url下载原始图像(png格式),即时对其进行转换(不保存到光盘)并另存为jpg。
代码如下:
import os
import io
import requests
from PIL import Image
...
r = requests.get(img_url, stream=True)
if r.status_code == 200:
i = Image.open(io.BytesIO(r.content))
i.save(os.path.join(out_dir, 'image.jpg'), quality=85)
它可以工作,但是当我尝试使用r.iter_content()监视下载进度(为将来的进度条)时,如下所示:
r = requests.get(img_url, stream=True)
if r.status_code == 200:
for chunk in r.iter_content():
print(len(chunk))
i = Image.open(io.BytesIO(r.content))
i.save(os.path.join(out_dir, 'image.jpg'), quality=85)
我收到此错误:
Traceback (most recent call last):
File "E:/GitHub/geoportal/quicklookScrape/temp.py", line 37, in <module>
i = Image.open(io.BytesIO(r.content))
File "C:\Python35\lib\site-packages\requests\models.py", line 736, in content
'The content for this response was already consumed')
RuntimeError: The content for this response was already consumed
那么有可能监视下载进度以及获取数据本身之后的情况吗?
使用时r.iter_content()
,您需要将结果缓冲在某处。不幸的是,我找不到任何将内容附加到内存中的对象的示例,通常iter_content
用于无法或不应该将文件一次全部加载到内存中的情况。但是,您可以tempfile.SpooledTemporaryFile
按照此答案中的说明使用对其进行缓冲:https : //stackoverflow.com/a/18550652/4527093。这将防止将映像保存到磁盘(除非映像大于指定的大小max_size
)。然后,您可以Image
从创建tempfile
。
import os
import io
import requests
from PIL import Image
import tempfile
buffer = tempfile.SpooledTemporaryFile(max_size=1e9)
r = requests.get(img_url, stream=True)
if r.status_code == 200:
downloaded = 0
filesize = int(r.headers['content-length'])
for chunk in r.iter_content(chunk_size=1024):
downloaded += len(chunk)
buffer.write(chunk)
print(downloaded/filesize)
buffer.seek(0)
i = Image.open(io.BytesIO(buffer.read()))
i.save(os.path.join(out_dir, 'image.jpg'), quality=85)
buffer.close()
编辑为include chunk_size
,这会将更新限制为每1kb而不是每个字节进行一次更新。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句