gpt4 book ai didi

python - 如何在 GdkPixbuf.Pixbuf 上呈现文本

转载 作者:太空宇宙 更新时间:2023-11-04 01:15:24 31 4
gpt4 key购买 nike

我正在尝试使用 Python 和 Gdk 3 将文本添加到 Pixbuf。

我已经在网上搜索关于这个主题的信息几个小时了,看来我需要从 pixbuf 创建一个 cairo 上下文。不幸的是,我对开罗的经验为零,但我已经能够将这段代码放在一起:

from gi.repository import Gdk

def put_text(pixbuf, text, x, y):
#create a Gdk.Window
window_attr= Gdk.WindowAttr()
window_attr.width= pixbuf.get_width()
window_attr.height= pixbuf.get_height()
window_attr.window_type= Gdk.WindowType.OFFSCREEN
#~ window_attr.window_type= Gdk.WindowType.TEMP
window_attr.redirect= True
#~ window_attr.redirect= False
window= Gdk.Window(None, window_attr, Gdk.WindowAttributesType(0))

#make a cairo context from the window
context= Gdk.cairo_create(window)
Gdk.cairo_set_source_pixbuf(context, pixbuf, 0, 0)

#render text
context.move_to(x, y)
context.set_font_size(15)
context.show_text(text)

#get the resulting pixbuf
surface= context.get_target()
result= Gdk.pixbuf_get_from_surface(surface, 0, 0, surface.get_width(), surface.get_height())

#~ window.destroy()
return result

这至少不会导致我的程序崩溃。然而,它产生的 pixbuf 是完全透明的。谁能告诉我我做错了什么,或者是否有更好的方法来做到这一点?

最佳答案

我终于设法生成了工作代码。显然使用 from gi.repository import cairo 是一个大错误。

from gi.repository import Gdk
import cairo

def put_text(pixbuf, text, x, y):
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, pixbuf.get_width(), pixbuf.get_height())
context = cairo.Context(surface)

Gdk.cairo_set_source_pixbuf(context, pixbuf, 0, 0)
context.paint() #paint the pixbuf

#add the text
fontsize= 20
context.move_to(x, y+fontsize)
context.set_font_size(fontsize)
context.set_source_rgba(0,0,0,1)
context.show_text(text)

#get the resulting pixbuf
surface= context.get_target()
pixbuf= Gdk.pixbuf_get_from_surface(surface, 0, 0, surface.get_width(), surface.get_height())

return pixbuf

关于python - 如何在 GdkPixbuf.Pixbuf 上呈现文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24979367/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com