使用pyglet使图像的一部分透明

时间:2017-12-10 17:24:03

标签: opengl pyglet

我有两张照片,"沙漠"图像结束"冬天"图像:

import pyglet


desert_img = pyglet.image.load('assets/desert.jpg')
desert = pyglet.sprite.Sprite(desert_img, x=50, y=50)

winter_img = pyglet.image.load('assets/winter.jpg')
winter = pyglet.sprite.Sprite(winter_img, x=0, y=0)

window = pyglet.window.Window()


@window.event
def on_draw():
    winter.draw()
    desert.draw()

pyglet.app.run()

结果是:result

我想画一个"透明度"在沙漠图像上(冬季图像应该在这个方块中可见)。可能吗 ?怎么做?

我发现许多问题允许对图像本身进行透明化(png,alpha ...但不是我想要的)。

1 个答案:

答案 0 :(得分:1)

根据Torxed建议,将图像内容替换为透明字节,我们希望将其透明:

import io
from PIL import Image
import pyglet
from PIL.PngImagePlugin import PngImageFile


def replace_content_with_transparency(img: PngImageFile, x, y, width, height):
    pixels = img.load()
    for i in range(x, width):
        for j in range(y, height):
            pixels[i, j] = (0, 0, 0, 0)


desert_png = Image.open('assets/desert.png')
replace_content_with_transparency(desert_png, 32, 32, 123, 123)

fake_file = io.BytesIO()
desert_png.save(fake_file, format='PNG')

desert_img = pyglet.image.load('img.png', file=fake_file)
desert = pyglet.sprite.Sprite(desert_img, x=50, y=50)

winter_img = pyglet.image.load('assets/winter.jpg')
winter = pyglet.sprite.Sprite(winter_img, x=0, y=0)

window = pyglet.window.Window()


@window.event
def on_draw():
    winter.draw()
    desert.draw()

pyglet.app.run()

image with square of transparency