python - 在 Python 中获取 GIF 图像的第一帧?

标签 python python-3.x request urllib gif

Getting the first frame of a GIF image without downloading all the other frames

↑ 这个帖子和我想知道的问题差不多。 但就我而言,我使用的是 Python 3.6 和 urllib。

import urllib
import requests

img_file = urllib.request.urlopen(img_url, timeout=10)

f = open('/img/' + img_name, 'wb')
f.write(img_file.read())
f.close()

我正在使用此代码获取图像文件。但是对于GIF或者移动jpg(GIF文件扩展名为jpg)文件,下载时间太长。

有没有办法只下载动画的第一帧?

最佳答案

我不会为您写完整的东西,这将涉及解析 GIF 文件的二进制内容,但这里有一个使用流行的第三方 requests module 增量下载文件的示例(使用其文档的 section 中的信息)。希望这会给您一个好的起点。

import requests

img_url = 'https://upload.wikimedia.org/wikipedia/commons/d/d3/Newtons_cradle_animation_book_2.gif'
#img_filename = 'test.gif'

response = requests.get(img_url, stream=True)
if response.status_code != 200:
    print('Error:', response.status_code)
else:
    header = response.raw.read(6)
    print(header)  # b'GIF89a'

#    # Download whole file in chunks and save locally.
#    with open(img_filename, 'wb') as f:
#        for chunk in response.iter_content(chunk_size=128):
#            f.write(chunk)

print('done')

关于python - 在 Python 中获取 GIF 图像的第一帧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55327556/

相关文章:

python - 集合中的正则表达式

python - 有没有更好的方法来编写这些 if 语句

python-3.x - BayesSearchCV 在 SGDClassifier 参数调整期间不起作用

java - 将对象绑定(bind)到 JSP 页面上的控件

python - 如何迭代 pyspark.sql.Column?

python - Tensorflow:如何编码和读取bmp图像?

python - 在没有嵌套循环的情况下访问字典的嵌套级别

java - 在java代码中提交表单时request.getParameter()获取null?

javascript - 如何在 Node.js 中向 Post 请求添加查询

python - WebHook 接收带有 +(加号)的字符串数据,其中空格应该是