在pygame中使用pixels_alpha设置alpha

时间:2013-07-06 19:00:34

标签: python pygame

我正在使用pygame进行图像编辑(不显示)。 (是的,我知道还有其他选项,比如PIL /枕头,但是pygame 应该为此工作。)

我想绘制并保存图像,我根据公式单独设置每个像素的alpha值(我正在绘制一个复杂的RGBA轮廓)。 pixels_alpha似乎是正确的方法。但是,当我更改pixels_alpha时,它会被忽略,图像会保持透明。这是我的代码......

import pygame as pg
import os
def init_transparent(img_width, img_height):
    """
    Create a new surface with width and height, starting with transparent
    background. This part works!
    """
    os.environ['SDL_VIDEODRIVER'] = 'dummy'
    pg.init()
    pg.display.init()
    # next command enables alpha
    # see http://stackoverflow.com/questions/14948711/
    pg.display.set_mode((img_width, img_height), 0, 32)
    # pg.SRCALPHA is a flag that turns on per-pixel alpha.
    return pg.Surface((img_width, img_height), pg.SRCALPHA)

def make_semitransparent_image():
    surf = init_transparent(20, 20)
    # alphas should be a direct reference to the alpha data in surf
    alphas = pg.surfarray.pixels_alpha(surf)
    # alphas is a uint8-dtype numpy array. Right now it's all zeros.
    for i in range(20):
        for j in range(20):
            # Since pixels_alpha gave me a uint8 array, I infer that
            # alpha=255 means opaque. (Right?)
            alphas[i,j] = 200
    pg.image.save(surf, '/home/steve/Desktop/test.png')

make_semitransparent_image()

同样,它保存了图像,但无论我设置alphas的值是什么,图像看起来都完全透明。我在这做错了什么? (使用Python 2.7,pygame 1.9.1release。)(提前致谢!)

1 个答案:

答案 0 :(得分:1)

Pygame文档说只要结果数组存在,pixels_array()就会锁定曲面,并且可能无法正确绘制锁定曲面。似乎他们也没有正确保存。在调用image.save()之前,您需要丢弃alphas surfarray对象。这可以通过在del alphas之前添加image.save()来完成。

(请注意,这更像是一种解决方法,而不是一个正确的修复。添加del alphas只能对CPython(而不是PyPy,Jython,IronPython)产生可靠的效果。也许你可以真正“关闭”一个surfarray对象,就像关闭文件或忘记文件一样?)