Paepoi

Paepoi » PyGObject Tips » GdkPixbuf(PyGObject) Tips

GdkPixbuf(PyGObject) Tips

# 最終更新日 2026.01.03

GdkPixbuf – 2.0 の簡易な解説。

画像の変換
画像ファイルを WebP に変換する例、多分 Web 製作者以外は必要が無いので
#!/usr/bin/env python3

'''
    python3 test.py *.png
    のように引数に画像を指定
'''

import gi, sys, os, re
gi.require_version('GdkPixbuf', '2.0')
from gi.repository import GdkPixbuf

for filename in sys.argv[1:]:
    if re.search(r'\.(jpe?g|png|gif)$', filename, re.I):
        text = os.path.splitext(filename)[0]
        pixbuf = GdkPixbuf.Pixbuf.new_from_file(filename)
        pixbuf.savev(f'{text}.webp', 'webp')

画像のリサイズ
画像ファイルを縮小し WebP に変換する場合
#!/usr/bin/env python3

'''
    python3 test.py *.png
    のように引数に画像を指定
'''

import gi, sys, os, re
gi.require_version('GdkPixbuf', '2.0')
from gi.repository import GdkPixbuf

# 縮小後の最大サイズを指定
MAX_SIZE = 300

for filename in sys.argv[1:]:
    if re.search(r'\.(jpe?g|png|gif|webp)$', filename, re.I):
        pixbuf = GdkPixbuf.Pixbuf.new_from_file(filename)
        aw = ah = MAX_SIZE
        w = pixbuf.get_width()
        h = pixbuf.get_height()
        if w > aw or h > ah:
            cleate = True
            if (aw * h) > (ah * w):
                width = w * ah // h
                height = ah
            else:
                width = aw
                height = h * aw // w
            smallpix = pixbuf.scale_simple(width, height, GdkPixbuf.InterpType.BILINEAR)
            # webp に変換して保存
            text = os.path.splitext(filename)[0]
            smallpix.savev(f'{text}-{width}x{height}.webp', 'webp')

画像の回転
enum PixbufRotation は反時計回り
#!/usr/bin/env python3

'''
    python3 test.py *.png
    のように引数に画像を指定
'''

import gi, sys, os, re
gi.require_version('GdkPixbuf', '2.0')
from gi.repository import GdkPixbuf

for filename in sys.argv[1:]:
    if re.search(r'\.(jpe?g|png|gif|webp)$', filename, re.I):
        pixbuf = GdkPixbuf.Pixbuf.new_from_file(filename)
        rotatepix = pixbuf.rotate_simple(GdkPixbuf.PixbufRotation.CLOCKWISE)
        text = os.path.splitext(filename)[0]
        rotatepix.savev(f'{text}-r90.webp', 'webp')

画像の反転
flip メソッドの引数が True なら横反転 False なら上下反転
#!/usr/bin/env python3

'''
    python3 test.py *.png
    のように引数に画像を指定
'''

import gi, sys, os, re
gi.require_version('GdkPixbuf', '2.0')
from gi.repository import GdkPixbuf

for filename in sys.argv[1:]:
    if re.search(r'\.(jpe?g|png|gif|webp)$', filename, re.I):
        pixbuf = GdkPixbuf.Pixbuf.new_from_file(filename)
        rotatepix = pixbuf.flip(True)
        text = os.path.splitext(filename)[0]
        rotatepix.savev(f'{text}-flip.webp', 'webp')

Copyright(C) sasakima-nao All rights reserved 2002 --- 2026.