wxPython - mit img2py.py PNG erstellen.

Plattformunabhängige GUIs mit wxWidgets.
Antworten
2bock
User
Beiträge: 94
Registriert: Freitag 12. September 2003, 07:58
Wohnort: 50.9333300 / 6.3666700

Hi zusammen.

Ich hab eine Frage. Ich probiere jetzt schon etwas herum und versuche bilder in PNG (als Code in eine py Datei) zu "konvertieren". Laut Skript sieht die Befehlszeile bei mit folgendermaßen aus.

C:\Programme\Python23\Lib\site-packages\wx\tools> img2py.py -n GetAchtung -c -a -u -i achtung.png bild.py

Aber es passiert nichts. Also wo ist der Fehler?
Können nur bestimmte Bild konvertiert werden? Sprich nur ähm, Icons?

Danke schon mal vorab für eure Ratschläge.

Greetz 2bock :roll: :roll:
Milan
User
Beiträge: 1078
Registriert: Mittwoch 16. Oktober 2002, 20:52

2bock hat geschrieben:Aber es passiert nichts. Also wo ist der Fehler?
Hi. Wahrscheinlich steckt der fehler in der img2py.py :roll: ... Frage: wie sieht die Datei denn aus?
2bock_not_logged

Ähm das ist die Datei aus wxPython 2.5. Und an der habe ich nichts mehr verändert. Ich wollte jetzt eigentlich ncith hier die ganze Datei rein pasten. ;-)
Milan
User
Beiträge: 1078
Registriert: Mittwoch 16. Oktober 2002, 20:52

Hi. Ok, dann hab ich nix gesagt :wink: . Ich hab nur wxPython nicht installiert und hab gedacht, du hast dir was selbst geschrieben um das dann in wxPython anzuwenden. Entschuldigung...
Christopy
User
Beiträge: 131
Registriert: Montag 15. Dezember 2003, 22:39

Das Tool in site-package/wx/tools funktioniert bei mir auch nicht. (ist anscheinend nur dazu da das wx zu löschen). Aber das Original in /site-packages/wxPython/tools funktioniert problemlos. Versuchs damit mal.

Aso... hab ja immer noch die 2.4er Version. Hoffe das ist in 2.5 gleich geblieben...
2bock_not_logged

Könntest Du mir die Datei, bzw. den Code zukommen lassen? Also wenn's bei Dir klappt, dann sollte das ja auch bei mir funtzen.

Greetz 2bock 8)
Christopy
User
Beiträge: 131
Registriert: Montag 15. Dezember 2003, 22:39

Ich poste das mal ganz dreist hier rein. Hoffe da hat niemand was gegen...

img2py.py

Code: Alles auswählen

#----------------------------------------------------------------------
# Name:        wxPython.tools.img2py
# Purpose:     Convert an image to Python code.
#
# Author:      Robin Dunn
#
# RCS-ID:      $Id: img2py.py,v 1.2.2.3 2003/01/21 00:04:33 RD Exp $
# Copyright:   (c) 2002 by Total Control Software
# Licence:     wxWindows license
#----------------------------------------------------------------------


"""
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

Options:

    -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.

    -n <name>      Normally generic names (getBitmap, etc.) are used for the
                   image access functions.  If you use this option you can
                   specify a name that should be used to customize the access
                   fucntions, (getNameBitmap, etc.)

    -c             Maintain a catalog of names that can be used to reference
                   images.  Catalog can be accessed via catalog and index attributes
                   of the module.  If the -n <name> option is specified then <name>
                   is used for the catalog key and index value, otherwise
                   the filename without any path or extension is used as the key.

    -a             This flag specifies that the python_file should be appended
                   to instead of overwritten.  This in combination with -n will
                   allow you to put multiple images in one Python source file.

    -u             Don't use compression.  Leaves the data uncompressed.

    -i             Also output a function to return the image as a wxIcon.

"""

#
# Changes:
#    - Cliff Wells <LogiplexSoftware@earthlink.net>
#      20021206: Added catalog (-c) option.
#


import sys, os, glob, getopt, tempfile
import cPickle, cStringIO, zlib
import img2img
from wxPython import wx


def crunch_data(data, compressed):
    # compress it?
    if compressed:
        data = zlib.compress(data, 9)

    # convert to a printable format, so it can be in a Python source file
    data = repr(data)

    # This next bit is borrowed from PIL.  It is used to wrap the text intelligently.
    fp = cStringIO.StringIO()
    data = data + " "  # buffer for the +1 test
    c = i = 0
    word = ""
    octdigits = "01234567"
    hexdigits = "0123456789abcdef"
    while i < len(data):
        if data[i] != "\\":
            word = data[i]
            i = i + 1
        else:
            if data[i+1] in octdigits:
                for n in range(2, 5):
                    if data[i+n] not in octdigits:
                        break
                word = data[i:i+n]
                i = i + n
            elif data[i+1] == 'x':
                for n in range(2, 5):
                    if data[i+n] not in hexdigits:
                        break
                word = data[i:i+n]
                i = i + n
            else:
                word = data[i:i+2]
                i = i + 2

        l = len(word)
        if c + l >= 78-1:
            fp.write("\\\n")
            c = 0
        fp.write(word)
        c = c + l

    # return the formatted compressed data
    return fp.getvalue()



def main(args):
    if not args or ("-h" in args):
        print __doc__
        return

    append = 0
    compressed = 1
    maskClr = None
    imgName = ""
    icon = 0
    catalog = 0

    try:
        opts, fileArgs = getopt.getopt(args, "auicn:m:")
    except getopt.GetoptError:
        print __doc__
        return

    for opt, val in opts:
        if opt == "-a":
            append = 1
        elif opt == "-u":
            compressed = 0
        elif opt == "-n":
            imgName = val
        elif opt == "-m":
            maskClr = val
        elif opt == "-i":
            icon = 1
        elif opt == "-c":
            catalog = 1

    if len(fileArgs) != 2:
        print __doc__
        return

    image_file, python_file = fileArgs

    # convert the image file to a temporary file
    tfname = tempfile.mktemp()
    ok, msg = img2img.convert(image_file, maskClr, None, tfname, wx.wxBITMAP_TYPE_PNG, ".png")
    if not ok:
        print msg
        return

    data = open(tfname, "rb").read()
    data = crunch_data(data, compressed)
    os.unlink(tfname)

    if append:
        out = open(python_file, "a")
    else:
        out = open(python_file, "w")

    if catalog:
        pyPath, pyFile = os.path.split(python_file)
        imgPath, imgFile = os.path.split(image_file)

        if not imgName:
            imgName = os.path.splitext(imgFile)[0]
            print "\nWarning: -n not specified. Using filename (%s) for catalog entry." % imgName

        old_index = []
        if append:
            # check to see if catalog exists already (file may have been created
            # with an earlier version of img2py or without -c option)
            oldSysPath = sys.path[:]
            sys.path = [pyPath] # make sure we don't import something else by accident
            mod = __import__(os.path.splitext(pyFile)[0])
            if 'index' not in dir(mod):
                print "\nWarning: %s was originally created without catalog." % python_file
                print "         Any images already in file will not be cataloged.\n"
                out.write("\n# ***************** Catalog starts here *******************")
                out.write("\n\ncatalog = {}\n")
                out.write("index = []\n\n")
                out.write("class ImageClass: pass\n\n")
            else: # save a copy of the old index so we can warn about duplicate names
                old_index[:] = mod.index[:]
            del mod
            sys.path = oldSysPath[:]

    out.write("#" + "-" * 70 + "\n")
    if not append:
        out.write("# This file was generated by %s\n#\n" % sys.argv[0])
        out.write("from wxPython.wx import wxImageFromStream, wxBitmapFromImage\n")
        if icon:
            out.write("from wxPython.wx import wxEmptyIcon\n")
        if compressed:
            out.write("import cStringIO, zlib\n\n\n")
        else:
            out.write("import cStringIO\n\n\n")

        if catalog:
            out.write("catalog = {}\n")
            out.write("index = []\n\n")
            out.write("class ImageClass: pass\n\n")

    if compressed:
        out.write("def get%sData():\n"
                  "    return zlib.decompress(\n%s)\n\n"
                  % (imgName, data))
    else:
        out.write("def get%sData():\n"
                  "    return \\\n%s\n\n"
                  % (imgName, data))


    out.write("def get%sBitmap():\n"
              "    return wxBitmapFromImage(get%sImage())\n\n"
              "def get%sImage():\n"
              "    stream = cStringIO.StringIO(get%sData())\n"
              "    return wxImageFromStream(stream)\n\n"
              % tuple([imgName] * 4))
    if icon:
        out.write("def get%sIcon():\n"
                  "    icon = wxEmptyIcon()\n"
                  "    icon.CopyFromBitmap(get%sBitmap())\n"
                  "    return icon\n\n"
                  % tuple([imgName] * 2))

    if catalog:
        if imgName in old_index:
            print "Warning: %s already in catalog." % imgName
            print "         Only the last entry will be accessible.\n"
        old_index.append(imgName)
        out.write("index.append('%s')\n" % imgName)
        out.write("catalog['%s'] = ImageClass()\n" % imgName)
        out.write("catalog['%s'].getData = get%sData\n" % tuple([imgName] * 2))
        out.write("catalog['%s'].getImage = get%sImage\n" % tuple([imgName] * 2))
        out.write("catalog['%s'].getBitmap = get%sBitmap\n" % tuple([imgName] * 2))
        if icon:
            out.write("catalog['%s'].getIcon = get%sIcon\n" % tuple([imgName] * 2))
        out.write("\n\n")

    if imgName:
        n_msg = ' using "%s"' % imgName
    else:
        n_msg = ""
    if maskClr:
        m_msg = " with mask %s" % maskClr
    else:
        m_msg = ""
    print "Embedded %s%s into %s%s" % (image_file, n_msg, python_file, m_msg)


if __name__ == "__main__":
    main(sys.argv[1:])

Desweiteren wird img2img.py benötigt.

img2img.py

Code: Alles auswählen

#----------------------------------------------------------------------
# Name:        wxPython.tools.img2img
# Purpose:     Common routines for the image converter utilities.
#
# Author:      Robin Dunn
#
# RCS-ID:      $Id: img2img.py,v 1.2.2.2 2003/01/21 00:04:33 RD Exp $
# Copyright:   (c) 2002 by Total Control Software
# Licence:     wxWindows license
#----------------------------------------------------------------------


import sys, os, glob, getopt
from wxPython.wx import *

if wxPlatform == "__WXGTK__":
    # some bitmap related things need to have a wxApp initialized...
    app = wxPySimpleApp()

wxInitAllImageHandlers()

def convert(file, maskClr, outputDir, outputName, outType, outExt):
    if os.path.splitext(file)[1].lower() == ".ico":
        icon = wxIcon(file, wxBITMAP_TYPE_ICO)
        img = wxBitmapFromIcon(icon)
    else:
        img = wxBitmap(file, wxBITMAP_TYPE_ANY)

    if not img.Ok():
        return 0, file + " failed to load!"
    else:
        if maskClr:
            om = img.GetMask()
            mask = wxMaskColour(img, maskClr)
            img.SetMask(mask)
            if om is not None:
                om.Destroy()
        if outputName:
            newname = outputName
        else:
            newname = os.path.join(outputDir,
                                   os.path.basename(os.path.splitext(file)[0]) + outExt)
        if img.SaveFile(newname, outType):
            return 1, file + " converted to " + newname
        else:
            img = wxImageFromBitmap(img)
            if img.SaveFile(newname, outType):
                return 1, "ok"
            else:
                return 0, file + " failed to save!"




def main(args, outType, outExt, doc):
    if not args or ("-h" in args):
        print doc
        return

    outputDir = ""
    maskClr = None
    outputName = None

    try:
        opts, fileArgs = getopt.getopt(args, "m:n:o:")
    except getopt.GetoptError:
        print __doc__
        return

    for opt, val in opts:
        if opt == "-m":
            maskClr = val
        elif opt == "-n":
            outputName = val
        elif opt == "-o":
            outputDir = val

    if not fileArgs:
        print doc
        return

    for arg in fileArgs:
        for file in glob.glob(arg):
            if not os.path.isfile(file):
                continue
            ok, msg = convert(file, maskClr, outputDir, outputName,
                              outType, outExt)
            print msg

Ich bin mir aber recht sicher, dass Du die Dateien auch hast. Hast Du mal unter site-package/wxpython/tools nachgesehen?
2bock_not_logged

So ich versuchs jetzt mal Merci

Greetz 2bock :wink: :wink:
2bock_not_logged

Also mittlerweile hab ich echt den Überblick verloren. Ich denke jetzt liegt der Fehler bei mir. Habe eigentlich alle relevanten Skripte kontrolliert.

Also Situation ist folgende. Ich habe im Ordner \\Python23\Lib\site-packages\wxPython\tools\ ein Bild mit dem Namen achtung.bmp liegen.

In der Kommandobox bin ich im richtigen Pfad.

So jetzt kommt der Befehl:

img2py.py -n getAchtung -c -a achtung.bmp Achtung.py

Resultat: Nix gar nix.

Habe ich hier etwas absolut wichtiges vergessen? Ich weiß es gibt noch mehr Parameter, aber ich wüßte nicht welche von den restl. unbedingt erforderlich wären damit etwas funktioniert.

Grettz 2bock :wink:
Christopy_ohne_login

Und genau das (img2py.py -n getAchtung -c -a achtung.bmp Achtung.py) funktioniert bei mir.
Bild
Zumindest etwas sollte er doch irgendwas machen. Gibts noch nichtmal eine Fehlermeldung?
Werde heute Abend mal die 2.5.1 Version installieren. Mal sehen ob's daran liegt.
2bock_not_logged

Ne da kommt bei mir nichts. Gar nichts.

Das steht in der Konsole.
------------------------------------------------------------------------
C:\Programme\Python23\Lib\site-packages\wxPython\tools>img2py.py -n getAchtung -c -a achtung.bmp Achtung.py

C:\Programme\Python23\Lib\site-packages\wxPython\tools>

Ich wäre ja schon dankbar für ne Meldung.

Greetz 2bock
:wink: :?: :mrgreen:
2bock_not_logged

Wenn ich die zeile wie folgt eingebe, dann wird zumindest schon einmal die Achtung.py erzeugt. Allerdings enthält sie nichts.

img2py.py -n getAchtung -c -a <achtung.bmp> Achtung.py
2bock_not_logged

Also hier als Beispiel meine Batchdatei. Ich verwende immer noch wxPython 2.5

Code: Alles auswählen

@echo off

C:\Programme\Python23\pythonw.exe C:\Programme\Python23\Lib\site-packages\wx\tools\img2py.py -n GetAchtung -c -a C:\test.bmp c:\Achtung.py 

:wink: :wink:
Christopy
User
Beiträge: 131
Registriert: Montag 15. Dezember 2003, 22:39

pythonw.exe? Das unterdrückt ja auch alle Ausgaben in der Eingabeaufforderung...

Nimm mal python.exe!
2bock_not_logged

Also jetzt klappts bei mir. ich denke es liegt daran, das nur absolute Pfadangaben akzeptiert werden. Jetzt hab ich nur noch eine Sache wo ich dran sitze. Ich muß die Streams in die Anwendung einbinden.

Greetz 2bock :wink:
Antworten