Rya*_*yan 2 transparency image python-imaging-library pycairo
这是我的代码:
进口开罗
导入操作系统
从 PIL 导入图像
图像大小 = (512,128)
表面 = cairo.ImageSurface(cairo.FORMAT_ARGB32, *imagesize)
cr = cairo.Context(表面)
cr.select_font_face("Verdana", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
cr.set_font_size(24)
cr.set_source_rgb(1, 1, 1)
...
surface.write_to_png("MyImage.png")
如您所见,我正在为此 PNG 绘制一些白色文本,但背景默认为不透明的黑色。如何使 png 透明,以便只显示白色文本?
小智 5
我能够使用 set_source_rgba() 设置透明背景,并使用 0.0 作为 alpha 值:
cr.set_source_rgba(0.0, 0.0, 0.0, 0.0) # transparent black
cr.rectangle(0, 0, 512, 128)
cr.fill()
Run Code Online (Sandbox Code Playgroud)
然后,我还必须确保使用以下内容编写文本:
# set writing color to white
cr.set_source_rgb(1, 1, 1)
# write text
cr.move_to(100,50)
cr.show_text("hello")
# commit to surface
cr.stroke()
Run Code Online (Sandbox Code Playgroud)
这是对我有用的完整代码:
import os
from PIL import Image
imagesize = (512,128)
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, *imagesize)
cr = cairo.Context(surface)
# paint background
cr.set_source_rgba(0.0, 0.0, 0.0, 0.0) # transparent black
cr.rectangle(0, 0, 512, 128)
cr.fill()
# setup font
cr.select_font_face("Verdana", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMA
cr.set_font_size(24)
cr.set_source_rgb(1, 1, 1)
# write with font
cr.move_to(100,50)
cr.show_text("hello")
# commit to surface
cr.stroke()
# save file
surface.write_to_png("MyImage.png")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3391 次 |
| 最近记录: |