python gif_python 将png图片格式转换生成gif动画

先看知乎上面的一个连接

用Python写过哪些【脑洞大开】的小工具?

这个哥们通过爬气象网站的气象雷达图,生成一个gif的动态图。非常有趣且很实用,那咱也实现下。

我们先实现一个从GIF提取帧的代码

我们这有个gif

540840-20170622104455507-1160319948.gif

代码如下:

from PIL importImageimportsysdefprocessImage(infile):try:

im=Image.open(infile)exceptIOError:print ("Cant load", infile)

sys.exit(1)

i=0

mypalette=im.getpalette()try:while 1:

im.putpalette(mypalette)

new_im= Image.new("RGBA", im.size)

new_im.paste(im)

new_im.save('image\\a'+str(i)+'.png')

i+= 1im.seek(im.tell()+ 1)exceptEOFError:pass #end of sequence

processImage('source.gif')

生成效果:

540840-20170622104750835-405164031.png

从gif提取frame是不是很简单,只需要一个PIL库搞定

但从frame生成gif就麻烦了,因为我们使用的是py3,网上一大堆代码用的是py2.*的 比如PythonMagick 、 images2gif

还有部分手写gif文件头部GIF89a,调用帧palette、NETSCAPE2.0写入图像等,你们都运行成功了,为什么我没有运行成功呢?

唉!

python就是牛,库如此之多,虽然本人Py一般般,但有前人为你写诗,您只要尾行加句号就可以了。这里我说的是imageio

下载地址: https://pypi.python.org/pypi/imageio (Version:2.2.0 by 2017-05-25)

importmatplotlib.pyplot as pltimportimageio,os

images=[]

filenames=sorted((fn for fn in os.listdir('.') if fn.endswith('.png')))for filename infilenames:

images.append(imageio.imread(filename))

imageio.mimsave('gif.gif', images,duration=1)

OK! gif生成了!

imageio.help('gif')

540840-20170622141245929-1575187242.png

其实,PIL自身也有一个save方法,里面有一个‘save_all’ 参数,意思就是save多个,当format指定为gif时,生成的便是gif的动画

from PIL importImage

im=Image.open("a0.png")

images=[]

images.append(Image.open('a1.png'))

images.append(Image.open('a2.png'))

im.save('gif.gif', save_all=True, append_images=images,loop=1,duration=1,comment=b"aaabb")

读取第一帧,将第一个帧的像素设置为gif像素

python将png图片格式转换生成gif动画已经可以实现了,但我们这里要实现的是获取气象雷达图生成GIF。

1.获取数据

获取数据,我们使用pquery

from pyquery importPyQuery as pq

d= pq('http://products.weather.com.cn/product/radar/index/procode/JC_RADAR_AZ9210_JB')

DomTree= d('#slideform #slide option')

540840-20170622112538835-240218692.png

2.下载气象雷达png图

想这个用Image.open 直接打开url的文件路径就可以

images.append(Image.open('http://pi.weather.com.cn/i/product/pic/l/sevp_aoc_rdcp_sldas_ebref_az9210_l88_pi_20170621014800000.png'))

那肯定是失败的:

Traceback (most recent call last):

File"E:/project/test2/my.py", line 29, in images.append(Image.open('http://pi.weather.com.cn/i/product/pic/l/sevp_aoc_rdcp_sldas_ebref_az9210_l88_pi_20170621014800000.png'))

File"C:\Python36\lib\site-packages\PIL\Image.py", line 2410, inopen

fp= builtins.open(filename, "rb")

OSError: [Errno22] Invalid argument: 'http://pi.weather.com.cn/i/product/pic/l/sevp_aoc_rdcp_sldas_ebref_az9210_l88_pi_20170621014800000.png'

异想天开呀!!!

imageio支持url文件路径 参考: http://imageio.readthedocs.io/en/latest/examples.html

importimageioimportvisvis as vv

im= imageio.imread('http://upload.wikimedia.org/wikipedia/commons/d/de/Wikipedia_Logo_1.0.png')

vv.imshow(im)

使用requests 库保存图片

importrequests

r= requests.get('http://pi.weather.com.cn/i/product/pic/l/sevp_aoc_rdcp_sldas_ebref_az9210_l88_pi_20170621014800000.png', timeout=3)

file= open('b1.png', 'wb')

size=file.write(r.content)

file.close()

540840-20170622113312710-1114619482.png

3.生成气象雷达GIF图

python 生成gif在上面我们已经说到两种方法,一种是imageio 另一种是PIL自带save_all,这里我们直接写一个类封装方法

源码如下:

#-*- coding: UTF8 -*-

importrequestsfrom pyquery importPyQuery as pqimportos, sysimportimageiofrom PIL importImage'''天气预报.gif 生成class'''

classweatherForecast():def __init__(self, weatherSite, path, endpng, savemodel):

self.savemodel=savemodelif notos.path.exists(path):

os.makedirs(path)defgetPic(self):'''获取资源'''

print('获取pic')

d=pq(weatherSite)

DomTree= d('#slideform #slide option') #获取DOM节点option 标签

num = 100

for bigpic inDomTree.items():

pic= bigpic.attr('bigpic') #获取bigpic 属性指

num += 1self.download(pic,'a' + str(num) + '.png') #下载pic

print('pic下载成功,共下载' + str(num - 100) + '个png')

self.download(endpng,'a1200.png') #下载end.png

self.download(endpng, 'a1201.png')

self.download(endpng,'a1202.png')

self.download(endpng,'a1203.png')defdownload(self, url, fname):'''下载pic

:return images size'''size=0try:

r= requests.get(url, timeout=3)

file= open(path + fname, 'wb')

size=file.write(r.content)

file.close()except:pass

returnsizedefgetGIF(self):'''生成gif'''images=[]print('执行开始')

self.getPic()#获取图片资源

filenames = sorted(fn for fn in os.listdir(path) if fn.endswith('.png'))if self.savemodel == 1: #imageio方法

for filename infilenames:

images.append(imageio.imread(path+filename))print('执行conversion操作')

imageio.mimsave('weather.gif', images, duration=0.5, loop=1) #duration 每帧间隔时间,loop 循环次数

print('完成……')elif self.savemodel == 2: #PIL 方法

imN = 1

for filename infilenames:if imN == 1: #执行一次 im的open操作,PIL在保存gif之前,必须先打开一个生成的帧,默认第一个frame的大小、调色

im = Image.open(path +filename)

imN= 2images.append(Image.open(path+filename))print('执行conversion操作')

im.save('weather.gif', save_all=True, append_images=images, loop=1, duration=500,

comment=b"this is my weather.gif")print('完成……')'''注:loop循环次数在浏览器有效果,用看图软件不起作用'''

if __name__ == "__main__":

weatherSite= "http://products.weather.com.cn/product/radar/index/procode/JC_RADAR_AZ9210_JB" #上海南汇

path = 'images/' #png 图片存储位置

endpng = 'http://images.cnblogs.com/cnblogs_com/dcb3688/982266/o_end.png' #因gif是循环播放,end png 区分新loop

savemodel = 1 #1:imageio保存图片, 2:PIL保存图片

weatherForecast =weatherForecast(weatherSite, path, endpng, savemodel)

weatherForecast.getGIF()

sys.exit()

也可以修改gif尺寸大小,先修改png大小

defdownload(self, url, fname):'''下载pic

:return images size'''size=0try:

r= requests.get(url, timeout=3)

file= open(path + fname, 'wb')

size=file.write(r.content)

file.close()#修改图片大小,原:x=640*y=480 = 320*240

ima = Image.open(path +fname)

(x, y)= ima.size #read image size

x_s = 320y_s= int((y * x_s) / x) ##calc height based on standard width

out = ima.resize((x_s, y_s), Image.ANTIALIAS) #resize image with high-quality

out.save(path +fname)except:pass

return size

images目录

540840-20170622114131210-961596058.png

生成气象雷达图gif

540840-20170622114517976-2077122312.gif

4.外部访问气象雷达图

脚步写好了,如何让别人也能访问呢,直接仍到公网IP的website目录就行了,然后写一个crontab定时脚步,每5分钟生成一次

*/5 * * * * python /home/wwwroot/www/web/static/weather/weather_forecast.py #每5分钟执行天气查询脚本

在这里,如果执行crontab定时脚步,代码生成的gif就要指定位置,否则生成的gif会在/root 目录里面

imageio.mimsave('/home/wwwroot/www/web/static/weather/weather.gif', images, duration=0.5, loop=1) # duration 每帧间隔时间,loop 循环次数

540840-20170622115947554-1700543520.gif

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/434271.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

HTTP代理原理以及HTTP隧道技术

通过HTTP协议与代理服务器建立连接,协议信令中包含要连接到的远程主机的IP和端口号,如果有需要身份验证的话还需要加上授权信息,服务器收到信令后首先进行身份验证,通过后便与远程主机建立连接,连接成功之后会返回给客…

goland环境配置_Goland辅助工具goimports和gomodules

1、goimports工具goimports工具是Go官方提供的一种工具,它能够为我们自动格式化 Go 语言代码并对所有引入的包进行管理,包括自动增删依赖的包引用、将依赖包按字母序排序并分类。我们在使用Goland IDE的时候,建议使用goimports工具。它具备包…

NSString 中包含中文字符时转换为NSURL

NSString中如果包括中文字符的话转换为NSURL得到的值为nil,在网上搜了下,用stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding可以解决,代码如下:NSString *str [NSString stringWithUTF8String:surl.c_str()]; …

石头剪刀布python代码_python实现石头剪刀布程序

本文实例为大家分享了python实现石头剪刀布的具体代码,供大家参考,具体内容如下 概述: 如果你和我一样是一个有着其他语言基础的编程者,那我想这个小程序对于你来说是小case。由于本人初学Python,就先拿这个熟悉熟悉一…

ubuntu/wireshark --Lua: Error during loading: [string /usr/share/wireshark/init.lua]:45问题解决

错误如下: 解决方案:修改init.lua 直接运行wireshark的话会报错: Lua: Error during loading: [string "/usr/share/wireshark/init.lua"]:45: dofile has been disabled 要对其进行修改,终端运行 sudo gedit /usr…

中高德地图只显示某一城市_Excel实用知识:从零开始,一步步制作属于你自己的三维演示地图...

说明本文是视频内容的图文整理版。原版视频可以在文末观看三维地图操作详解这是一份原始表格,点击表内任意一个单元格,使用Ctrl和T,将这张表转换为动态表,点击插入,三维地图。重命名图层为销售地图一,在位置…

HttpModules 管道过滤 自定义页面

IIS里.HTML扩展名默认ASP.NET不做请求管理,如果要在HttpModules中拦截html的请求,从而做一些流量判断或url伪静态重定向的操作,请将IIS的扩展名.HTML映射到“C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll” iis管理器 - 站点 - 处理程序映射,增…

Linux软连接和硬链接

1.Linux链接概念 Linux链接分两种,一种被称为硬链接(Hard Link),另一种被称为符号链接(Symbolic Link)。默认情况下,ln命令产生硬链接。 【硬连接】 硬连接指通过索引节点来进行连接。在Linux的…

python内置函数分类_Python 69个内置函数分类总结

1 内置函数 Python3解释器中内置了69个常用函数,属于底层的函数,它们到处可用。有些对大家来说比较熟悉,比如abs(), max(), sum()... 也有一些比较陌生,比如locals(), all(), compile(), getattr()... 今天按照类别扼要总结。 2 类…

pyspark 修改python版本_python – Pyspark从日期到字符串更改列的类型

我有以下数据帧:corr_temp_df[(vacationdate, date),(valueE, string),(valueD, string),(valueC, string),(valueB, string),(valueA, string)]现在我想将列vacationdate的数据类型更改为String,这样数据帧也会采用这种新类型并覆盖所有条目的数据类型数据.例如.写…

ubuntu下IP、DNS配置

一、配置ip ubuntu的网络配置信息放在 /etc/network/interfaces 中,如果配置动态获取ip,则在上述文件中加入以下内容:auto eth0iface eth0 inet dhcp如果配置静态ip,则添加如下内容:auto eth0 iface eth0 inet statica…

python向空列表添加列表_Python列表核心知识点汇总

千里之行,始于足下。要练成一双洞悉一切的眼睛,还是得先把基本功扎扎实实地学好。今天带大家仔细温习一下Python的列表。温故而知新,不亦说乎。当然,温习的同时也要发散思考,因为有些看似无关紧要的、约定俗成的语言习…

伪指令endp告诉汇编程序_全国2004年10月高等教育自学考试微型计算机原理及应用试题历年试卷...

&nbsp&nbsp全国2004年10月高等教育自学考试微型计算机原理及应用试题课程代码:02277一、单项选择题(本大题共15小题,每小题1分,共15分)在每小题列出的四个备选项中只有一个是符合题目要求的,请将其代码填写在题后的括号内…

C语言 if的条件相关

Expressions connected by && or || are evaluated left to right, and it is guaranteed that evaluation will stop as soon as the truth or falsehood is known. ----引用自 The C Programming Language 此句表明在C语言中如果多个条件用&&或者||连接的情况…

关于config_site.h文件【译】

编译前的准备 创建config_site.h文件 config_site.h文件的作用 创建config_site.h文件时的注意点 创建config_site.h文件 在编译源代码之前,必须先创建pjlib/include/pj/config_site.h文件(可以为空) 提示:当使用基于Makefile的编译系统,…

sharepoint2010的弹出等待提示的对话框

根据MSDN的资料。我做了个测试&#xff0c;代码如下&#xff1a; <% Assembly Name"$SharePoint.Project.AssemblyFullName$" %> <% Assembly Name"Microsoft.Web.CommandUI, Version14.0.0.0, Cultureneutral, PublicKeyToken71e9bce111e9429c" …

java中输出值保留四位小数_Java工程师(3).变量和数据类型

变量什么是变量变量是内存中的一块存储空间&#xff0c;用于保存Java程序准备使用的数据。可以为变量赋予一个简短并易于记忆的名字方便我们使用变量的值。int 变量的声明因为经常要保存一些数据&#xff0c;所以变量是很常用的。使用变量必须先声明变量&#xff1a;int 变量的…

扫描路径_npj: 纳米团簇表面的自动扫描—吸附位点和扩散路径

海归学者发起的公益学术平台分享信息&#xff0c;整合资源交流学术&#xff0c;偶尔风月金属纳米团簇常用于催化&#xff0c;因具有较高的分散性&#xff0c;应用领域不断扩大。与较大的金属纳米颗粒相比&#xff0c;其固有活性通常要高出数倍。这种高出的催化活性主要归因于其…

pjsip的编译及简单使用

1.下载下载地址&#xff1a;http://www.pjsip.org/download.htm我下载的是pjproject-1.12.zip2.编译将下载的文件解压后&#xff0c;目录下有pjproject-vs8.sln&#xff0c;可以直接使用vs2005打开&#xff0c;目录下的readme.txt文件中有编译说明&#xff0c;关于windows下的注…

innodb 悲观锁 乐观锁_mysql乐观锁、悲观锁、共享锁、排它锁、行锁、表锁

mysql乐观锁、悲观锁、共享锁、排它锁、行锁、表锁乐观锁总是假设最好的情况&#xff0c;每次去拿数据的时候都认为别人不会修改&#xff0c;所以不会上锁&#xff0c;但是在更新的时候会判断一下在此期间别人有没有去更新这个数据&#xff0c;可以使用版本号机制和CAS算法实现…