gifsicle的Python封装
感觉gifsicle 还是一款比较强大的gif图片处理软件,功能包括了:
1、对gif中所有帧的任意位置切割;
2、gif中任意帧的修改、分解,并提供多幅gif图片中的任意帧的合并操作
3、gif图片的缩小与放大,包括等比例的缩放。
4、控制gif的循环播放次数以及播放周期
5、and so on
在对Gifsicle的封装过程中,我主要是将其分成两部分(其实整个封装应该是三部分内容),首先是对传入图片的处理,接着对整体的输出图片处理。将每一张需要处理的图片创建一个实例,然后记录对这张图片的操作,最后将其添加进输出图片实例中,并对输出图片的相关修改操作,最后执行convert方法输出图片。
#! /usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'glcsnz123'
import os
import matplotlib
import commands
class GifInfo:#gifsicle -I
def __init__(self, imgfile):
if not os.path.isfile(imgfile): return
self.src = imgfile
self.__rotate = ""
self.__crops = ""
self.__resizes = ""
def resize_gif(self, width=None, height=None):
if width is None and height is None: return False
if width is None:
self.__resizes = " --resize-height %d " % height
return True
if height is None:
self.__resizes = " --resize-width %d " % width
return True
self.__resizes = " --resize %dx%d" % (width, height)
return True
def resize_fit_gif(self, width=None, height=None):
if width is None and height is None: return False
if width is None:
self.__resizes = " --resize-fit-height %d " % (height)
return True
if height is None:
self.__resizes = " --resize-fit-width %d " % (width)
return True
self.__resizes = " --resize-fit %dx%d " % (width, height)
return True
def fix_scale(self, Xscale, Yscale=None):
self.__resizes = " --scale " + str(Xscale / 100.0)
if Yscale is not None:
self.__resizes += "x" + str(Yscale / 100.0)
self.__resizes += " "
def rotate_gif(self, degree=0):
if degree == 90 or degree == "90":
self.__rotate = " --rotate-90 "
elif degree == 180 or degree == "180":
self.__rotate = " --rotate-180 "
elif degree == 270 or degree == "270":
self.__rotate = " --rotate-270 "
else:
return False
return True
def crop_gif_bypos(self, lefttop, rightdown):
if rightdown[0] < lefttop[0] or rightdown[1] < lefttop[1]: return False
self.__crops = " --crop " + ','.join(map(str, lefttop)) + "-" + ",".join(map(str, rightdown)) + " "
return True
def crop_gif_bywh(self, lefttop, wh):
if wh[0] <= 0 or wh[1] <= 0: return False
self.__crops = " --crop " + ",".join(map(str, lefttop)) + "+" + "x".join(map(str, wh)) + " "
return True
def __str__(self):
return " ".join([self.__crops, self.__rotate, self.__resizes, self.src])
class Gifsicle:
def __init__(self):
pass
def convert(self, infile, outfile=None):
if outfile is None:
res = commands.getstatusoutput("gifsicle --batch " + str(infile))
if res[0] == 0:
return True
return False
res = commands.getstatusoutput("gifsicle " + str(infile) + " > " + outfile)
if res[0] == 0:
return True
return False
if __name__ == '__main__':
gi = GifInfo("/home/glcsnz123/images/psb.gif")
gi.crop_gif_bywh((23, 23), (220, 220))
gi.rotate_gif(90)
gi.fix_scale(95, 95)
gf = Gifsicle()
gf.convert(gi, "/home/glcsnz123/images/test.gif")
print str(gi)