Cairoで透過PNGの背景合成
Cairoでアルファチャンネル付きのPNGファイルと背景を描画したcanvasを合成する方法。Pythonで次のような感じ。ちなみにこういう感じでフォントの指定(select_font_face)もやっている。
image = cairo.ImageSurface.create_from_png("image_with_alpha.png") width = image.get_width() height = image.get_height() bg = cairo.ImageSurface(cairo.FORMAT_ARGB32,width, height) crbg = cairo.Context(bg) crbg.set_source_rgb(1,1,1) crbg.rectangle(0,0,width,height) crbg.fill() cr = cairo.Context(image) cr.set_font_size(120) cr.select_font_face("monospace", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD) cr.set_source_rgb(0,0,0) cr.move_to(0,128 - 16) cr.show_text("%s" % 'ABC') crbg.set_source_surface(image) crbg.paint()
画像のsurfaceを作成してsurfaceからContextを作って文字を書き込み。surface自体を背景となるsurfaceに書き込むという流れ