여러 이미지들을 합쳐 하나의 gif 파일로 만드는 오픈소스를 작성해보자!
import glob # 내 디렉토리에 있는 파일들을 한번에 가져와 리스트로 변환
from PIL import Image
pip install image
기능별로 확인
path_in = '../project/images/*.png' # glob 덕분에, 확장자를 정한 후 다 가져올 수 있게된다.
path_out = '../project/image_out/result.gif'
img, *images = [Image.open(f).resize((320,240), Image.ANTIALIAS)
for f in sorted(glob.glob(path_in))]
# ANITALIAS: 이미지의 여백 방지 -> 모두 같은 규격의 이미지를 가지면서, 여백이 생기지 않도록.
img.save(
fp=path_out, # fp: filename -> save() 메소드에 정의되어 있다.
format='GIF', # GIF 형식으로 저장
append_images=images, # 패킹된 images 리스트를 append
save_all=True,
duration=300, # GIF 파일의 움직임 속도를 조절 (숫자가 클 수록 전환속도가 느리다)
loop=0
)
클래스형으로 작성
- 위의 기능단위 코드를 하나의 클래스 내부에서 정의한다.
- 즉 하나의 클래스로 모든 과정을 수행할 수 있도록 정의.
class GifConverter:
def __init__(self, path_in=None, path_out=None, resize=(320, 240)):
"""
opensource는 초반에 파라미터에 대해 설명을 해주는 것이 좋다
"""
self.path_in = path_in or './*.png'
self.path_out = path_out or './output.gif'
self.resize = resize
def convert_gif(self):
img, *images = \
[Image.open(f).resize(self.resize, Image.ANTIALIAS) for f in
sorted(glob.glob(self.path_in))] # ANITALIAS: 여백 방지
try:
img.save(
fp=self.path_out, # fp: filename -> save() 메소드에 정의되어 있다.
format="GIF",
append_images=images,
save_all=True,
duration=500,
loop=0
)
except IOError:
print('Cannot covert!', img)
# 배포 했을 때 아래 if조건이 없으면, 우리가 테스트 한 코드가 그대로 사용되기에, \
# __name__ == '__main__' 조건을 달아준다.
if __name__ == '__main__':
# 클래스
c = GifConverter('../project/images/*.png', '../project/image_out/result.gif', (320, 240))
c.convert_gif()
모두를 위한 파이썬 : 필수 문법 배우기 Feat. 오픈소스 패키지 배포 (Inflearn Original)