Re: PyEmbeddedImage - Huh What!
Eric Fahlgren <[email protected]>
| Newsgroups | gmane.comp.python.wxpython.devel |
|---|---|
| Message-ID | <CAP2Qz+VUX3TeHrv_Lvq5R4dE-Ep3B7Mij+GykuDbEkmgLxXy_g@mail.gmail.com> |
I use a modified version of Robin's img2py.py and generate an "art.py" file
that gets imported into my top-level gui wrappers.
Output looks like this:
>>> # Generated file, do not edit.
>>> # vim: set expandtab softtabstop=4 shiftwidth=4:
>>> from wx.lib.embeddedimage import PyEmbeddedImage
>>> _guiArt=dict()
>>>
>>> def addResource(resource, data):
>>> _guiArt[resource] = PyEmbeddedImage(data)
>>> def getResource(resource):
>>> return _guiArt.get(resource, None)
>>> def delResource(resource):
>>> if _guiArt.get(resource):
>>> _guiArt.pop(resource)
>>>
>>> def getImage(resource):
>>> embedded = getResource(resource)
>>> return embedded and embedded.Image
>>> def getBitmap(resource):
>>> embedded = getResource(resource)
>>> return embedded and embedded.Bitmap
>>>
>>> addResource('Appearance.png', # 356 bytes
>>>
"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAQAAAC1+jfqAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAu0lEQVQoz7WRsUrDYBRGT6TEwaFgcWt0z9RCi4PgIrp1a/AhfIVC"
>>>
"p07dHZ1DEKEdC4a/axU6uHUW38Cux0lMnLrkTBfuge9yP2ic6Hewy5g7BsA7K56jz5pnam6V3LQuzNWlQ2Njhy7VeXV97ZeFiZnBYGZi4c7pn/DityMwqBrAkTs/AFoA"
>>>
"TNhT1jJfWbCuhhz74IUdFwZ7nvjoZf3II+8tPffMK0/dOLP17w/gLTf0abPlKXprvoLD+QEwW2tYMK4WlgAAAABJRU5ErkJggg==")
Then I just run a shell script that basically does this:
> tools/img2py -o art.py resources/*.png
On Fri, Apr 28, 2017 at 6:36 AM, Metallicow <[email protected]>
wrote:
> I know that there are many ways to embed your images.
>
> What I am asking for is a "script" that does it all. Or to build a public
> "script" that does.
>
> How do you do it I ask?
>
> --
> You received this message because you are subscribed to the Google Groups
> "wxPython-dev" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> For more options, visit https://groups.google.com/d/optout.
>
--
You received this message because you are subscribed to the Google Groups "wxPython-dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [email protected].
For more options, visit https://groups.google.com/d/optout.
img2py.py
(text/plain, 6.3 KB)
#!/usr/bin/env python #------------------------------------------------------------------------------- # Name: Derived from wxPython.tools.img2py # Purpose: Convert an image to Python code. # # Author: Robin Dunn # # RCS-ID: $Id: img2py.py 9694 2017-02-27 19:54:31Z efahlgren $ # Copyright: (c) 2002 by Total Control Software # Licence: wxWindows license #------------------------------------------------------------------------------- # # Changes: # - Cliff Wells <[email protected]> # 20021206: Added catalog (-c) option. # # 12/21/2003 - Jeff Grimmett ([email protected]) # V2.5 compatibility update # # 2/25/2007 - Gianluca Costa ([email protected]) # -Refactorization of the script-creation code in a specific "img2py()" function # -Added regex parsing instead of module importing # -Added some "try/finally" statements # -Added default values as named constants # -Made some parts of code a bit easier to read # -Updated the module docstring # -Corrected a bug with EmptyIcon # # 11/26/2007 - Anthony Tuininga ([email protected]) # -Use base64 encoding instead of simple repr # -Remove compression which doesn't buy anything in most cases and # costs more in many cases # -Use wx.lib.embeddedimage.PyEmbeddedImage class which has methods # rather than using standalone methods # #------------------------------------------------------------------------------- """ 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 [-m color] [-o outputFile] imageFile... -o outputFile Name of file into which encoded image output will be directed. Defaults to sys.stdout if unspecified. -m <#rrggbb> If the original image has a mask or transparency defined it will be used by default. You can use this option to override the default or provide a new mask by specifying a colour in the image to mark as transparent. """ #------------------------------------------------------------------------------- from base64 import b64encode import getopt import os import sys import tempfile import wx from wx.tools import img2img app = None DEFAULT_MASKCLR = None totalLength = 0 #------------------------------------------------------------------------------- def convert(fileName, maskClr, outputDir, outputName, outType, outExt): # if the file is already the right type then just use it directly if maskClr == DEFAULT_MASKCLR and fileName.upper().endswith(outExt.upper()): if outputName: newname = outputName else: newname = os.path.join(outputDir, os.path.basename(os.path.splitext(fileName)[0]) + outExt) file(newname, "wb").write(file(fileName, "rb").read()) return 1, "ok" else: return img2img.convert(fileName, maskClr, outputDir, outputName, outType, outExt) #------------------------------------------------------------------------------- def img2py(imageFile, outFile, maskClr=DEFAULT_MASKCLR): """ Converts an image file to a data structure, writes it to outFile. """ global app, totalLength app = app or wx.GetApp() or wx.App(False) # convert the image file to a temporary file tfname = tempfile.mktemp() try: ok, msg = convert(imageFile, maskClr, None, tfname, wx.BITMAP_TYPE_PNG, ".png") if not ok: print msg return lines = [] data = b64encode(open(tfname, "rb").read()) length = len(data) while data: part = data[:128] data = data[128:] output = ' "%s"' % part if not data: output += ")" lines.append(output) data = "\n".join(lines) finally: if os.path.exists(tfname): os.remove(tfname) imgPath, imgFile = os.path.split(imageFile) outFile.write("addResource('%s', # %d bytes\n%s\n\n" % (imgFile, length, data)) totalLength += length #------------------------------------------------------------------------------- def openOutput(pythonFile): addHeader = not os.path.exists(pythonFile) outFile = open(pythonFile, "ab") if addHeader: outFile.write("""\ # Generated file, do not edit. # vim: set expandtab softtabstop=4 shiftwidth=4: from wx.lib.embeddedimage import PyEmbeddedImage _guiArt=dict() def addResource(resource, data): _guiArt[resource] = PyEmbeddedImage(data) def getResource(resource): return _guiArt.get(resource, None) def delResource(resource): if _guiArt.get(resource): _guiArt.pop(resource) def getImage(resource): embedded = getResource(resource) return embedded and embedded.Image def getBitmap(resource): embedded = getResource(resource) return embedded and embedded.Bitmap """) return outFile #------------------------------------------------------------------------------- def main(args=None): if not args: args = sys.argv[1:] if not args or ("-h" in args): print __doc__ return maskClr = DEFAULT_MASKCLR try: opts, fileArgs = getopt.gnu_getopt(args, "m:o:") except getopt.GetoptError as error: print str(error) print __doc__ return outFile = sys.stdout stdout = True for opt, val in opts: if opt == "-m": maskClr = val elif opt == "-o": outFile = openOutput(val) stdout = False print "Writing to %s" % val if len(fileArgs) < 1: print __doc__ return fileArgs.sort() for imageFile in fileArgs: if not stdout: print " Embedding %s" % imageFile img2py(imageFile, outFile, maskClr) outFile.write("# %d bytes total data\n" % totalLength) if not stdout: outFile.close() #------------------------------------------------------------------------------- if __name__ == "__main__": main(sys.argv[1:]) #-------------------------------------------------------------------------------