Start_python’s diary

ふたり暮らし

アラフィフ夫婦のフリーランスプラン

pythonでgifを作成する

本日の課題と目標

gifの保存方法を学ぶ

 

 

はじめに

ブログにgif画像を貼りたくなりgifを作りたくなりました。サンプルコードを参照に「虹色の四角形が大きくなるプログラム」を作っていきます。

 

 

プログラム

from PIL import Image, ImageDraw



images = []



width = 200

center = width // 2

color_1 = (255, 0, 0)

color_2 = (255, 165, 0)

color_3 = (255, 255, 0)

color_4 = (0, 128, 0)

color_5 = (0, 255, 255)

color_6 = (0, 0, 255)

color_7 = (128, 0, 128)



max_radius = int(center * 1.4)

step = 2



for i in range(0, max_radius, step):

    im = Image.new('RGB', (width, width), color_1)

    draw = ImageDraw.Draw(im)

    draw.rectangle((center / 5 - i, center / 5 - i, center * 9 / 5 + i, center * 9 / 5 + i), fill=color_2)

    draw.rectangle((center * 2 / 5 - i, center * 2 / 5 - i, center * 8 / 5 + i, center * 8 / 5 + i), fill=color_3)

    draw.rectangle((center * 3 / 5 - i, center * 3 / 5 - i, center * 7 / 5 + i, center * 7 / 5 + i), fill=color_4)

    draw.rectangle((center * 4 / 5 - i, center * 4 / 5 - i, center * 6 / 5 + i, center * 6 / 5 + i), fill=color_5)

    draw.rectangle((center - i, center - i, center + i, center + i), fill=color_6)

    if center / 5 < i:

        draw.rectangle((center * 6 / 5 - i, center * 6 / 5 - i, center * 4 / 5 + i, center * 4 / 5 + i), fill=color_7)

    if center * 2 / 5 < i:

        draw.rectangle((center * 7 / 5 - i, center * 7 / 5 - i, center * 3 / 5 + i, center * 3 / 5 + i), fill=color_1)

    if center * 3 / 5 < i:

        draw.rectangle((center * 8 / 5 - i, center * 8 / 5 - i, center * 2 / 5 + i, center * 2 / 5 + i), fill=color_2)

    if center * 4 / 5 < i:

        draw.rectangle((center * 9 / 5 - i, center * 9 / 5 - i, center * 1 / 5 + i, center * 1 / 5 + i), fill=color_3)

    if center * 5 / 5 < i:

        draw.rectangle((center * 10 / 5 - i, center * 10 / 5 - i, center * 0 / 5 + i, center * 0 / 5 + i), fill=color_4)

    if center * 6 / 5 < i:

        draw.rectangle((center * 11 / 5 - i, center * 11 / 5 - i, center * -1 / 5 + i, center * -1 / 5 + i), fill=color_5)

        

    images.append(im)



images[0].save('data/dst/pillow_imagedraw.gif', save_all=True, append_images=images[1:], optimize=False, duration=40, loop=0)

 

f:id:Start_python:20191104102101g:plain

 

 

解説

Image.save()でGIFとして保存


im.save('out.gif', save_all=True, append_images=[im1, im2, ...])

 

 

Drawオブジェクトの生成


オブジェクト名 = ImageDraw.Draw(背景の画像データ)

 

 

ellipseメソッドの使い方

図形描画メソッドのひとつで楕円(円)を描画する


オブジェクト名.ellipse( (左上のx座標, 左上のy座標, 右下のx座標, 右下のy座標), fill=(255, 255, 255) )


fill は図形を塗りつぶす色を設定する。

outline は図形の枠線の色を設定する。

 

 

オブジェクトとは?

物体(データ)のこと


メソッドとは?

方法・方式(オブジェクトの属性)のこと

変数や値に付けて呼び出す

 

 

参考サイト

note.nkmk.me

note.nkmk.me

 

 

保存ファイル

lesson27.py

lesson28.py

 

 

文責:Luke