user9123
user9123

Reputation: 601

Is it possible to put an image directly into a python program

I made a simple game in python using the pygame library and it worked great. The only problem is that it required images which meant that if I wanted to share my creation, I'd have to put it all in a zip (or other archive) which is a pain, especially when you're constantly updating the program.

I know this sounds a bit stupid but is there a way of encoding an image file so that it can be stored within the python file itself? For example, when opening an image in a text editor, you can see the image as text. Could I perhaps paste this into python and use some library to decode it back into an image? If not, I might just put the images on a server and make the program retrieve them each time. I figured it wouldn't hurt to ask though.

Upvotes: 0

Views: 437

Answers (1)

MegaIng
MegaIng

Reputation: 7886

Yes, this is possible and actually quite easy. You first have to decode the surface to an string using the pygame.image.tostring(image, format) function. It takes the surface and a format (probably RGB or RGBA). You can then save the returned string in your script:

string = pygame.image.tostring(surface, 'RGB')
print(string) # A long bytes string (b'\xff\xff\x00\xff\xff\x00\xff\xff\x00\xff\xff\x00\xff\xff\x00\xff....')

You then load the image with pygame.image.fromstring(image, size, format) (Where size is the expected surface size)

string = b'\xff\xff\x00\xff\xff\x00\xff\xff\x00\xff\xff\x00\xff\xff\x00\xff....'
surface = pygame.image.fromstring(string, surface.get_size(), 'RGB')
print(surface)

You just copy the output of tostring into the script.

Upvotes: 2

Related Questions