Как отобразить текст в GdkPixbuf.Pixbuf
Я пытаюсь добавить текст в Pixbuf, используя Python и Gdk 3.
Я искал в Интернете информацию об этой теме в течение нескольких часов, и, похоже, мне нужно создать каирский контекст из 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
Что, по крайней мере, не вызывает сбой моей программы. Тем не менее, изображение, которое он создает, полностью прозрачно. Может кто-нибудь сказать мне, что я делаю не так или есть лучший способ сделать это?
1 ответ
Решение
Мне наконец-то удалось создать рабочий код. Видимо используя 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