开发者

Is it possible to code images into a python script?

Instead of using directories to reference an image, is it possible to code a开发者_开发技巧n image into the program directly?


You can use the base64 module to embed data into your programs. From the base64 documentation:

>>> import base64
>>> encoded = base64.b64encode('data to be encoded')
>>> encoded
'ZGF0YSB0byBiZSBlbmNvZGVk' 
>>> data = base64.b64decode(encoded)
>>> data
'data to be encoded'

Using this ability you can base64 encode an image and embed the resulting string in your program. To get the original image data you would pass that string to base64.b64decode.


Try img2py script. It's included as part of wxpython (google to see if you can dl seperately).

img2py.py -- Convert an image to PNG format and embed it in a Python module with appropriate code so it can be loaded into a program at runtime. The benefit is that since it is Python source code it can be delivered as a .pyc or 'compiled' into the program using freeze, py2exe, etc. Usage:

img2py.py [options] image_file python_file


There is no need to base64 encode the string, just paste it's repr into the code


If you mean, storing the bytes that represent the image in the program code itself, you could do it by base64 encoding the image file, and setting a variable to that string.

You could also declare a byte array, where the contents of the array are the bytes that represent the image.

In both cases, if you want to operate on the image, you may need to decode the value that you have included in your source code.

Warning: you may be treading on a performance minefield here.

A better way might be to store the image/s in the directory structure of your module, and the loading it on demand (even caching it). You could write a generalized method/function that loads the right image based on some identifier which maps to the particular image file name that is part and parcel of your module.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜