python gif_python 将png图片格式转换生成gif动画
先看知乎上面的一個(gè)連接
用Python寫過哪些【腦洞大開】的小工具?
這個(gè)哥們通過爬氣象網(wǎng)站的氣象雷達(dá)圖,生成一個(gè)gif的動(dòng)態(tài)圖。非常有趣且很實(shí)用,那咱也實(shí)現(xiàn)下。
我們先實(shí)現(xiàn)一個(gè)從GIF提取幀的代碼
我們這有個(gè)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')
生成效果:
從gif提取frame是不是很簡單,只需要一個(gè)PIL庫搞定
但從frame生成gif就麻煩了,因?yàn)槲覀兪褂玫氖莗y3,網(wǎng)上一大堆代碼用的是py2.*的 比如PythonMagick 、 images2gif
還有部分手寫gif文件頭部GIF89a,調(diào)用幀palette、NETSCAPE2.0寫入圖像等,你們都運(yùn)行成功了,為什么我沒有運(yùn)行成功呢?
唉!
python就是牛,庫如此之多,雖然本人Py一般般,但有前人為你寫詩,您只要尾行加句號(hào)就可以了。這里我說的是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')
其實(shí),PIL自身也有一個(gè)save方法,里面有一個(gè)‘save_all’ 參數(shù),意思就是save多個(gè),當(dāng)format指定為gif時(shí),生成的便是gif的動(dòng)畫
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")
讀取第一幀,將第一個(gè)幀的像素設(shè)置為gif像素
python將png圖片格式轉(zhuǎn)換生成gif動(dòng)畫已經(jīng)可以實(shí)現(xiàn)了,但我們這里要實(shí)現(xiàn)的是獲取氣象雷達(dá)圖生成GIF。
1.獲取數(shù)據(jù)
獲取數(shù)據(jù),我們使用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')
2.下載氣象雷達(dá)png圖
想這個(gè)用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()
3.生成氣象雷達(dá)GIF圖
python 生成gif在上面我們已經(jīng)說到兩種方法,一種是imageio 另一種是PIL自帶save_all,這里我們直接寫一個(gè)類封裝方法
源碼如下:
#-*- coding: UTF8 -*-
importrequestsfrom pyquery importPyQuery as pqimportos, sysimportimageiofrom PIL importImage'''天氣預(yù)報(bào).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節(jié)點(diǎn)option 標(biāo)簽
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) + '個(gè)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('執(zhí)行開始')
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('執(zhí)行conversion操作')
imageio.mimsave('weather.gif', images, duration=0.5, loop=1) #duration 每幀間隔時(shí)間,loop 循環(huán)次數(shù)
print('完成……')elif self.savemodel == 2: #PIL 方法
imN = 1
for filename infilenames:if imN == 1: #執(zhí)行一次 im的open操作,PIL在保存gif之前,必須先打開一個(gè)生成的幀,默認(rèn)第一個(gè)frame的大小、調(diào)色
im = Image.open(path +filename)
imN= 2images.append(Image.open(path+filename))print('執(zhí)行conversion操作')
im.save('weather.gif', save_all=True, append_images=images, loop=1, duration=500,
comment=b"this is my weather.gif")print('完成……')'''注:loop循環(huán)次數(shù)在瀏覽器有效果,用看圖軟件不起作用'''
if __name__ == "__main__":
weatherSite= "http://products.weather.com.cn/product/radar/index/procode/JC_RADAR_AZ9210_JB" #上海南匯
path = 'images/' #png 圖片存儲(chǔ)位置
endpng = 'http://images.cnblogs.com/cnblogs_com/dcb3688/982266/o_end.png' #因gif是循環(huán)播放,end png 區(qū)分新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目錄
生成氣象雷達(dá)圖gif
4.外部訪問氣象雷達(dá)圖
腳步寫好了,如何讓別人也能訪問呢,直接仍到公網(wǎng)IP的website目錄就行了,然后寫一個(gè)crontab定時(shí)腳步,每5分鐘生成一次
*/5 * * * * python /home/wwwroot/www/web/static/weather/weather_forecast.py #每5分鐘執(zhí)行天氣查詢腳本
在這里,如果執(zhí)行crontab定時(shí)腳步,代碼生成的gif就要指定位置,否則生成的gif會(huì)在/root 目錄里面
imageio.mimsave('/home/wwwroot/www/web/static/weather/weather.gif', images, duration=0.5, loop=1) # duration 每幀間隔時(shí)間,loop 循環(huán)次數(shù)
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的python gif_python 将png图片格式转换生成gif动画的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 民生车车卡金卡返多少加油金
- 下一篇: python导出dxf图_在PDMS中使