PyGobject(八十四)GdkPixbuf.Pixbuf

GdkPixbuf图像处理
本文介绍gdk-pixbuf库中的Pixbuf结构及其方法,展示如何使用Pixbuf进行图像加载、缩放与动画制作。通过一个具体的Python示例程序,演示了Pixbuf在实际项目中的应用。

GdkPixbuf.Pixbuf

这是gdk-pixbuf库的主要结构。它被用于表示图像。它包含关于图像的像素数据、宽度和高度等信息。

这里写图片描述

Methods

方法修饰词方法名及参数
staticfrom_pixdata (pixdata, copy_pixels)
staticget_file_info (filename)
staticget_file_info_async (filename, cancellable, callback, *user_data)
staticget_file_info_finish (async_result)
staticget_formats ()
staticnew (colorspace, has_alpha, bits_per_sample, width, height)
staticnew_from_bytes (data, colorspace, has_alpha, bits_per_sample, width, height, rowstride)
staticnew_from_data (data, colorspace, has_alpha, bits_per_sample, width, height, rowstride, destroy_fn, *destroy_fn_data)
staticnew_from_file (filename)
staticnew_from_file_at_scale (filename, width, height, preserve_aspect_ratio)
staticnew_from_file_at_size (filename, width, height)
staticnew_from_inline (data, copy_pixels)
staticnew_from_resource (resource_path)
staticnew_from_resource_at_scale (resource_path, width, height, preserve_aspect_ratio)
staticnew_from_stream (stream, cancellable)
staticnew_from_stream_async (stream, cancellable, callback, *user_data)
staticnew_from_stream_at_scale (stream, width, height, preserve_aspect_ratio, cancellable)
staticnew_from_stream_at_scale_async (stream, width, height, preserve_aspect_ratio, cancellable, callback, *user_data)
staticnew_from_stream_finish (async_result)
staticnew_from_xpm_data (data)
staticsave_to_stream_finish (async_result)
add_alpha (substitute_color, r, g, b)
apply_embedded_orientation ()
composite (dest, dest_x, dest_y, dest_width, dest_height, offset_x, offset_y, scale_x, scale_y, interp_type, overall_alpha)
composite_color (dest, dest_x, dest_y, dest_width, dest_height, offset_x, offset_y, scale_x, scale_y, interp_type, overall_alpha, check_x, check_y, check_size, color1, color2)
composite_color_simple (dest_width, dest_height, interp_type, overall_alpha, check_size, color1, color2)
copy ()
copy_area (src_x, src_y, width, height, dest_pixbuf, dest_x, dest_y)
fill (pixel)
flip (horizontal)
get_bits_per_sample ()
get_byte_length ()
get_colorspace ()
get_has_alpha ()
get_height ()
get_n_channels ()
get_option (key)
get_options ()
get_pixels ()
get_rowstride ()
get_width ()
new_subpixbuf (src_x, src_y, width, height)
read_pixel_bytes ()
read_pixels ()
rotate_simple (angle)
saturate_and_pixelate (dest, saturation, pixelate)
save_to_bufferv (type, option_keys, option_values)
save_to_callbackv (save_func, user_data, type, option_keys, option_values)
savev (filename, type, option_keys, option_values)
scale (dest, dest_x, dest_y, dest_width, dest_height, offset_x, offset_y, scale_x, scale_y, interp_type)
scale_simple (dest_width, dest_height, interp_type)

Virtual Methods

Properties

NameTypeFlagsShort Description
bits-per-sampleintr/w/coThe number of bits per sample
colorspaceGdkPixbuf.Colorspacer/w/coThe colorspace in which the samples are interpreted
has-alphaboolr/w/coWhether the pixbuf has an alpha channel
heightintr/w/coThe number of rows of the pixbuf
n-channelsintr/w/coThe number of samples per pixel
pixel-bytesGLib.Bytesr/w/coReadonly pixel data
pixelsintr/w/coA pointer to the pixel data of the pixbuf
rowstrideintr/w/coThe number of bytes between the start of a row and the start of the next row
widthintr/w/coThe number of columns of the pixbuf

Signals

NameShort Description

例子

这里写图片描述
代码:

#!/usr/bin/env python3
# Created by xiaosanyu at 16/7/19
# section 132
# 
# author: xiaosanyu
# website: yuxiaosan.tk \
#          http://blog.youkuaiyun.com/a87b01c14
# created: 16/7/19

TITLE = "Pixbuf"
DESCRIPTION = """
A GdkPixbuf represents an image, normally in RGB or RGBA format.
Pixbufs are normally used to load files from disk and perform
image scaling.

This demo is not all that educational, but looks cool. It was written
by Extreme Pixbuf Hacker Federico Mena Quintero. It also shows
off how to use GtkDrawingArea to do a simple animation.

Look at the Image demo for additional pixbuf usage examples.
"""

import gi

gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk, GdkPixbuf, GLib
import os
from math import *

background_name = "background.jpg"
image_names = ("apple-red.png",
               "gnome-applets.png",
               "gnome-calendar.png",
               "gnome-foot.png",
               "gnome-gmush.png",
               "gnome-gimp.png",
               "gnome-gsame.png",
               "gnu-keys.png")
images = []
prefix = os.path.realpath(os.path.join(os.path.dirname(__file__), "Data"))
start_time = 0
CYCLE_TIME = 3000000


class PixbufsWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="Pixbuf demo")
        self.set_resizable(False)
        self.background = None
        self.back_width = 10
        self.back_height = 10
        rlt = self.load_pixbufs()
        if not rlt[0]:
            dialog = Gtk.MessageDialog(self,
                                       Gtk.DialogFlags.DESTROY_WITH_PARENT,
                                       Gtk.MessageType.ERROR,
                                       Gtk.ButtonsType.CLOSE,
                                       "Failed to load an image: %s" % rlt[1])

            dialog.run()
            dialog.destroy()

        else:
            self.set_size_request(self.back_width, self.back_height)

            self.pixbuf = GdkPixbuf.Pixbuf.new(GdkPixbuf.Colorspace.RGB, False, 8, self.back_width, self.back_height);

            da = Gtk.DrawingArea.new()

            da.connect("draw", self.draw_cb)

            self.add(da)

            da.add_tick_callback(self.on_tick, da)

    def load_pixbufs(self):
        if self.background:
            return True, ""  # already loaded earlier
        try:
            self.background = GdkPixbuf.Pixbuf.new_from_file(os.path.join(prefix, background_name))
            self.back_width = self.background.get_width()
            self.back_height = self.background.get_height()

            for image in image_names:
                images.append(GdkPixbuf.Pixbuf.new_from_file(os.path.join(prefix, image)))
        except GLib.Error as e:
            return False, e.message

        return True, ""

    def draw_cb(self, drawingarea, cr):
        Gdk.cairo_set_source_pixbuf(cr, self.pixbuf, 0, 0)
        cr.paint()

        return True

    def on_tick(self, da, frame_clock, *data):
        global start_time
        self.background.copy_area(0, 0, self.back_width, self.back_height,
                                  self.pixbuf, 0, 0)

        if start_time == 0:
            start_time = frame_clock.get_frame_time()

        current_time = frame_clock.get_frame_time()
        f = ((current_time - start_time) % CYCLE_TIME) / CYCLE_TIME

        xmid = self.back_width / 2.0
        ymid = self.back_height / 2.0

        radius = min(xmid, ymid) / 2.0

        for i, image in enumerate(images):
            r1 = Gdk.Rectangle()
            r2 = Gdk.Rectangle()
            dest = Gdk.Rectangle()

            ang = 2.0 * GLib.PI * i / len(images) - f * 2.0 * GLib.PI

            iw = image.get_width()
            ih = image.get_height()

            r = radius + (radius / 3.0) * sin(f * 2.0 * GLib.PI)

            xpos = floor(xmid + r * cos(ang) - iw / 2.0 + 0.5)
            ypos = floor(ymid + r * sin(ang) - ih / 2.0 + 0.5)

            k = sin(f * 2.0 * GLib.PI) if i & 1 else cos(f * 2.0 * GLib.PI)
            k = 2.0 * pow(k, 2)
            k = max(0.25, k)

            r1.x = xpos
            r1.y = ypos
            r1.width = iw * k
            r1.height = ih * k

            r2.x = 0
            r2.y = 0
            r2.width = self.back_width
            r2.height = self.back_height
            rlt = Gdk.rectangle_intersect(r1, r2)
            if rlt[0]:
                dest = rlt[1]
                image.composite(self.pixbuf,
                                dest.x, dest.y,
                                dest.width, dest.height,
                                xpos, ypos,
                                k, k,
                                GdkPixbuf.InterpType.NEAREST,
                                max(127, fabs(255 * sin(f * 2.0 * GLib.PI))) if (i & 1) else \
                                    max(127, fabs(255 * cos(f * 2.0 * GLib.PI))))

        da.queue_draw()

        return GLib.SOURCE_CONTINUE


def main():
    win = PixbufsWindow()
    win.connect("delete-event", Gtk.main_quit)
    win.show_all()
    Gtk.main()


if __name__ == "__main__":
    main()





代码下载地址:http://download.youkuaiyun.com/detail/a87b01c14/9594728

Table of Contents I. API Reference Initialization and Versions - Library version numbers. The GdkPixbuf Structure - Information that describes an image. Reference Counting and Memory Mangement - Functions for reference counting and memory management on pixbufs. File Loading - Loading a pixbuf from a file. File saving - Saving a pixbuf to a file. Image Data in Memory - Creating a pixbuf from image data that is already in memory. Inline data - Functions for inlined pixbuf handling. Scaling - Scaling pixbufs and scaling and compositing pixbufs Rendering - Rendering a pixbuf to a GDK drawable. Drawables to Pixbufs - Getting parts of a GDK drawable's image data into a pixbuf. Utilities - Utility and miscellaneous convenience functions. Animations - Animated images. GdkPixbufLoader - Application-driven progressive image loading. Module Interface - Extending gdk-pixbuf gdk-pixbuf Xlib initialization - Initializing the gdk-pixbuf Xlib library. Xlib Rendering - Rendering a pixbuf to an X drawable. X Drawables to Pixbufs - Getting parts of an X drawable's image data into a pixbuf. XlibRGB - Rendering RGB buffers to X drawables. II. Tools Reference gdk-pixbuf-csource - C code generation utility for GdkPixbuf images gdk-pixbuf-query-loaders - GdkPixbuf loader registration utility Index Index of deprecated symbols Index of new symbols in 2.2 Index of new symbols in 2.4 Index of new symbols in 2.6 Index of new symbols in 2.8 A. Porting applications from Imlib to gdk-pixbuf Introduction Differences between Imlib and gdk-pixbuf Initialization Memory management The Rendering Process Converting Applications to gdk-pixbuf Image loading and creation Rendering Images Scaling Images
### 安装特定版本的 PyGObject (3.36.0) 要安装指定版本的 PyGObject(例如 3.36.0),可以通过以下方式实现: #### 方法一:通过源码手动编译安装 可以下载对应版本的 PyGObject 和 GObject 的源码并进行编译安装。 1. 首先确保开发环境已准备好,包括必要的依赖项: ```bash sudo apt update && sudo apt upgrade -y sudo apt install -y libgirepository1.0-dev gcc libcairo2-dev pkg-config python3-dev gir1.2-gtk-3.0 python3-pip ``` 2. 下载所需版本的 `pygobject` 源码包。可以从官方仓库获取具体版本的 tarball 文件[^1]: ```bash wget https://github.com/pygobject/pygobject/archive/refs/tags/v3.36.0.tar.gz tar -xvzf v3.36.0.tar.gz cd pygobject-3.36.0/ ``` 3. 编译并安装: ```bash ./configure --prefix=/usr make sudo make install ``` 此过程会将指定版本的 PyGObject 安装到系统路径下。 --- #### 方法二:使用虚拟环境隔离安装 如果不想影响系统的全局 Python 环境,可以选择创建一个虚拟环境来安装特定版本的 PyGObject。 1. 创建并激活虚拟环境: ```bash python3 -m venv my_pygobject_env source my_pygobject_env/bin/activate ``` 2. 使用 `pip` 安装指定版本的 PyGObject 及其依赖项。需要注意的是,某些低级 C 库可能仍需手动安装。 ```bash pip install pycairo==1.20.1 # 对应兼容版本 pip install pygobject==3.36.0 # 显式指明版本号 ``` 注意:由于 PyGObject 是基于底层 C 扩展构建的,因此仅靠 `pip` 不一定能成功完成安装,特别是当缺少必要头文件时。此时需要回退至 **方法一** 或者额外配置开发工具链。 --- #### 方法三:利用 Debian 软件包管理器定制化安装 对于 Ubuntu/Debian 用户来说,还可以尝试自定义 `.deb` 包的方式安装目标版本的 PyGObject。 1. 准备工作同上,即安装基础依赖; 2. 制作假软件包以满足依赖关系解析需求: ```bash sudo apt-get install -y equivs equivs-control python-gobject_3.36.0 ``` 修改生成的控制文件中的字段(如名称、版本等)为期望值后再执行打包命令: ```bash equivs-build python-gobject_3.36.0 dpkg -i python-gobject_3.36.0.deb ``` 这种方法适用于更复杂的场景,尤其是涉及多个相互关联组件的情况下。 --- ### 注意事项 无论采用哪种方案,在操作前都建议备份当前的工作目录以及重要数据以防万一出现问题;另外还需确认所选版本与其他项目间是否存在潜在冲突或不兼容情况[^2]。 ```python import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, GdkPixbuf print(f"Installed GTK Version: {Gtk._version}") ``` 上述脚本可用于验证最终是否正确加载了预期版本的库函数集合。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sanxiaochengyu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值