BPL BPL - 1 year ago 130
Python Question

embedding resources in python scripts

I'd like to figure out how to embed binary content in a python script. For instance, I don't want to have any external files around (images, sound, ... ), I want all this content living inside of my python scripts.

Little example to clarify, let's say I got this small snippet:

from StringIO import StringIO
from PIL import Image, ImageFilter

embedded_resource = StringIO(open("Lenna.png", "rb").read())
im = Image.open(embedded_resource)

im_sharp = im.filter(ImageFilter.SHARPEN)

As you can see, the example is reading the external file 'Lenna.png'

enter image description here


How to proceed to embed "Lenna.png" as a resource (variable) into my python script. What's the fastest way to achieve this simple task using python?

Answer Source

The best way to go about this is converting your picture into a python string, and have it in a separate file called something like resources.py, then you simply parse it.

If you are looking to embed the whole thing inside a single binary, then you're looking at something like py2exe. Here is an example embedding external files

In the first scenario, you could even use base64 to (de)code the picture, something like this:

import base64
file = open('yourImage.png'); 
encoded = base64.b64encode(file.read())
data = base64.b64decode(encoded) # Don't forget to file.close() !
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download