py-sdl / py-sdl2

Python ctypes wrapper around SDL2
Other
304 stars 49 forks source link

PIL.Image can be used as an argument when creating a sprite #255

Closed minhalvp closed 1 year ago

minhalvp commented 1 year ago

PR Description

A PIL.Image can be directly inputted to the from_image function which is found in spritesystem.py. This allows the user to input a PIL image (that has been initialized in the code) into the from_image function instead of needing to save the image and load it.

You can use an image from your code like this:

img = Image.fromarray(frame) # img is a PIL image

sdl2.ext.init()
window = sdl2.ext.Window("window", size=(100,100))

factory = sdl2.ext.SpriteFactory(sdl2.ext.SOFTWARE)
sprite = factory.from_image(img)
spriterenderer = factory.create_sprite_render_system(window)
spriterenderer.render(sprite)

window.show()

Instead of saving the image in your code and loading it which is slow. Like this:

img = Image.fromarray(frame) # img is a PIL image
sdl2.ext.init()
RESOURCES = sdl2.ext.Resources(__file__, "images")

img.save("random\\images\\image.png") # Save img in the same directory
factory = sdl2.ext.SpriteFactory(sdl2.ext.SOFTWARE)
sprite = factory.from_image(RESOURCES.get_path("image.png")) # Load Image
window = sdl2.ext.Window("window", size=(100,100))

spriterenderer = factory.create_sprite_render_system(window)
spriterenderer.render(sprite)
window.show()

Merge Checklist

a-hurst commented 1 year ago

Thanks for this! Just FYI the SpriteSystem is no longer under active development (replaced by the revamped Renderer/Texture API), but I'm still happy to merge any improvements people offer.

I'm merging this into a temporary branch to fix a few things (add the change to news.rst, add a unit test to make sure it the method still works if PIL isn't installed), but will make sure you get credited properly in the changelog 🙂