【问题标题】:PyGI Edit Image ColorPyGI 编辑图像颜色
【发布时间】:2017-11-12 07:09:22
【问题描述】:

谁能告诉我如何使用 PyGI(或 PyGTK)更改图像颜色? 我需要方法或属性,如 CEGUI 中的“ImageColour”,改变图像的非 alpha 通道。例如: 我有一张照片,它只是白色的圆形。我需要在界面的不同地方使用这一轮,用不同的颜色。而且我不会再创建这一轮的副本,例如 bcs,我需要 256 种不同的颜色。 和图片示例:

This is picture with white round, what I've got

This is picture with round, what color I want to see

这是我用来改变颜色的函数:

image = gtk.Image()
image.set_from_file("images/button.png")
pix_buffer = image.get_pixbuf()
pix_buffer.fill(0xA32432FF)
image.set_from_pixbuf(pix_buffer)

这不能正常工作。那就是将完整图像填充到红色的四边形。

另一个想法是 modify_fg/modify_base,但这里只工作 modify_bg 只改变背景(而不改变白色)

【问题讨论】:

    标签: python user-interface colors pygtk


    【解决方案1】:

    我最近几天一直在玩这个,将pixbuf 视为像素的直接表示并不完全容易。原因之一是GdkPixbuf 软件确定了一个“行跨度”,这会导致图像寻址中的“跳跃”。

    在我可以进行更多调查之前,我发现的最简单的解决方案是将 pixbuf 转换为 PIL.Image,在那里执行操作,然后再转换回 pixbuf。这是进行转换的两个函数:

    def pixbuf2image(self, pxb):
        """ Convert GdkPixbuf.Pixbuf to PIL image """
        data = pxb.get_pixels()
        w = pxb.get_width()
        h = pxb.get_height()
        stride = pxb.get_rowstride()
        mode = "RGB"
        if pxb.get_has_alpha():
            mode = "RGBA"
        img = Image.frombytes(mode, (w, h), data, "raw", mode, stride)
        return img
    
    def image2pixbuf(self, img):
        """ Convert PIL or Pillow image to GdkPixbuf.Pixbuf """
        data = img.tobytes()
        w, h = img.size
        data = GLib.Bytes.new(data)
        pxb = GdkPixbuf.Pixbuf.new_from_bytes(data, GdkPixbuf.Colorspace.RGB,
                False, 8, w, h, w * 3)
        return pxb
    

    幸运的是,new_from_bytes 会自动考虑行跨度,并将data 中的连续字节以正确的方式保存在内存中。

    PIL(Python3 为Pillow)中,您可以对图像执行许多操作,包括逐像素访问。请注意pixbuf 始终使用RGB(A) 组件,因此您必须小心转换和操作!

    无论如何,如果您想直接构造图像,后一个函数显示如何将内存 (bytes) 数组转换为 GdkPixbuf

    【讨论】:

      猜你喜欢
      • 2015-09-12
      • 2021-10-17
      • 1970-01-01
      • 2017-04-23
      • 1970-01-01
      • 2016-05-10
      • 1970-01-01
      • 1970-01-01
      • 2020-02-07
      相关资源
      最近更新 更多