【问题标题】:How to output transparent PNG with Pycairo?如何使用 Pycairo 输出透明的 PNG?
【发布时间】:2012-02-15 19:42:18
【问题描述】:

这是我的代码:

进口开罗
导入操作系统
从 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 透明,以便只显示白色文本?

【问题讨论】:

    标签: image transparency python-imaging-library pycairo


    【解决方案1】:

    我能够使用 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()
    

    然后,我还必须确保使用以下内容编写文本:
    # 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()
    

    这是对我有用的完整代码:
    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_NORMAL)
    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")
    

    【讨论】:

      猜你喜欢
      • 2017-03-04
      • 2012-06-14
      • 2011-06-20
      • 2017-05-30
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 2018-10-09
      • 2019-01-03
      相关资源
      最近更新 更多