Пример #1
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)
Пример #2
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)
Пример #3
0
def img2py(image_file, python_file, append=DEFAULT_APPEND, compressed=DEFAULT_COMPRESSED, maskClr=DEFAULT_MASKCLR, imgName=DEFAULT_IMGNAME, icon=DEFAULT_ICON, catalog=DEFAULT_CATALOG):
    """
    Converts an image file to a data structure written in a Python file
    --image_file: string; the path of the source image file
    --python_file: string; the path of the destination python file
    --other arguments: they are equivalent to the command-line arguments
    """
    global app
    if not wx.GetApp():
        app = wx.PySimpleApp()
        
    # convert the image file to a temporary file
    tfname = tempfile.mktemp()
    try:
        ok, msg = img2img.convert(image_file, maskClr, None, tfname, wx.BITMAP_TYPE_PNG, ".png")
        if not ok:
            print msg
            return
            
        data = open(tfname, "rb").read()
        data = crunch_data(data, compressed)
    finally:
        if os.path.exists(tfname):
            os.remove(tfname)
    

    old_index = []
    if catalog and append:
        # check to see if catalog exists already (file may have been created
        # with an earlier version of img2py or without -c option)
        pyPath, pyFile = os.path.split(python_file)
        
        append_catalog = True
        
        sourcePy = open(python_file, "r")
        try:
            for line in sourcePy:
                
                if line == "catalog = {}\n":
                    append_catalog = False
                else:
                    lineMatcher = indexPattern.match(line)
                    if lineMatcher:
                        old_index.append(lineMatcher.groups()[0])
        finally:
            sourcePy.close()
                    
                    
        if append_catalog:
            out = open(python_file, "a")
            try:
                out.write("\n# ***************** Catalog starts here *******************")
                out.write("\n\ncatalog = {}\n")
                out.write("index = []\n\n")
                out.write("class ImageClass: pass\n\n")
            finally:
                out.close()
        
        
    
    if append:
        out = open(python_file, "a")
    else:
        out = open(python_file, "w")
        
    try:
        if catalog:
            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
    
        out.write("#" + "-" * 70 + "\n")
        if not append:
            out.write("# This file was generated by %s\n#\n" % sys.argv[0])
            out.write("from wx import ImageFromStream, BitmapFromImage, EmptyIcon\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 BitmapFromImage(get%sImage())\n\n"
                  "def get%sImage():\n"
                  "    stream = cStringIO.StringIO(get%sData())\n"
                  "    return ImageFromStream(stream)\n\n"
                  % tuple([imgName] * 4))
        if icon:
            out.write("def get%sIcon():\n"
                      "    icon = EmptyIcon()\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)
    finally:
        out.close()
Пример #4
0
def main(args):
    if not args or ("-h" in args):
        print __doc__
        return

    # some bitmap related things need to have a wxApp initialized...
    if wx.GetApp() is None:
        app = wx.PySimpleApp()

    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.BITMAP_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 wx from PIL import ImageFromStream, BitmapFromImage\n")
        if icon:
            out.write("from wx import EmptyIcon\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 BitmapFromImage(get%sImage())\n\n"
              "def get%sImage():\n"
              "    stream = cStringIO.StringIO(get%sData())\n"
              "    return ImageFromStream(stream)\n\n"
              % tuple([imgName] * 4))
    if icon:
        out.write("def get%sIcon():\n"
                  "    icon = EmptyIcon()\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)
Пример #5
0
def img2py(image_file, python_file,
           append=DEFAULT_APPEND,
           compressed=DEFAULT_COMPRESSED,
           maskClr=DEFAULT_MASKCLR,
           imgName=DEFAULT_IMGNAME,
           icon=DEFAULT_ICON,
           catalog=DEFAULT_CATALOG,
           functionCompatible=DEFAULT_COMPATIBLE,
           functionCompatibile=-1,   # typo version for backward compatibility
           ):
    """
    Converts an image file to a data structure written in a Python file
    --image_file: string; the path of the source image file
    --python_file: string; the path of the destination python file
    --other arguments: they are equivalent to the command-line arguments
    """
    
    # was the typo version used?
    if functionCompatibile != -1:
        functionCompatible = functionCompatibile
        
    global app
    if not wx.GetApp():
        app = wx.PySimpleApp()
        
    # convert the image file to a temporary file
    tfname = tempfile.mktemp()
    try:
        ok, msg = img2img.convert(image_file, maskClr, None, tfname, wx.BITMAP_TYPE_PNG, ".png")
        if not ok:
            print msg
            return

        lines = []
        data = b64encode(open(tfname, "rb").read())
        while data:
            part = data[:72]
            data = data[72:]
            output = '    "%s"' % part
            if not data:
                output += ")"
            lines.append(output)
        data = "\n".join(lines)
    finally:
        if os.path.exists(tfname):
            os.remove(tfname)

    old_index = []
    if catalog and append and python_file != '-':
        # check to see if catalog exists already (file may have been created
        # with an earlier version of img2py or without -c option)
        pyPath, pyFile = os.path.split(python_file)
        
        append_catalog = True
        
        sourcePy = open(python_file, "r")
        try:
            for line in sourcePy:
                
                if line == "catalog = {}\n":
                    append_catalog = False
                else:
                    lineMatcher = indexPattern.match(line)
                    if lineMatcher:
                        old_index.append(lineMatcher.groups()[0])
        finally:
            sourcePy.close()

        if append_catalog:
            out = open(python_file, "a")
            try:
                out.write("\n# ***************** Catalog starts here *******************")
                out.write("\n\ncatalog = {}\n")
                out.write("index = []\n\n")
            finally:
                out.close()

    if python_file == '-':
        out = sys.stdout
    elif append:
        out = open(python_file, "a")
    else:
        out = open(python_file, "w")
        
    try:
        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 name of image and/or catalog entry." % imgName

        out.write("#" + "-" * 70 + "\n")
        if not append:
            out.write("# This file was generated by %s\n#\n" % sys.argv[0])
            out.write("from wx.lib.embeddedimage import PyEmbeddedImage\n\n")        
            if catalog:
                out.write("catalog = {}\n")
                out.write("index = []\n\n")

        letters = []
        for letter in imgName:
            if not letter.isalnum():
                letter = "_"
            letters.append(letter)
        if not letters[0].isalpha() and letters[0] != '_':
            letters.insert(0, "_")
        varName = "".join(letters)

        out.write("%s = PyEmbeddedImage(\n%s\n" % (varName, data))

        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'] = %s\n" % (imgName, varName))

        if functionCompatible:
            out.write("get%sData = %s.GetData\n" % (varName, varName))
            out.write("get%sImage = %s.GetImage\n" % (varName, varName))
            out.write("get%sBitmap = %s.GetBitmap\n" % (varName, varName))
            if icon:
                out.write("get%sIcon = %s.GetIcon\n" % (varName, varName))

        out.write("\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)
    finally:
        if python_file != '-':
            out.close()
Пример #6
0
def img2py(image_file,
           python_file,
           append=DEFAULT_APPEND,
           compressed=DEFAULT_COMPRESSED,
           maskClr=DEFAULT_MASKCLR,
           imgName=DEFAULT_IMGNAME,
           icon=DEFAULT_ICON,
           catalog=DEFAULT_CATALOG,
           functionCompatibile=DEFAULT_COMPATIBLE):
    """
    Converts an image file to a data structure written in a Python file
    --image_file: string; the path of the source image file
    --python_file: string; the path of the destination python file
    --other arguments: they are equivalent to the command-line arguments
    """
    global app
    if not wx.GetApp():
        app = wx.PySimpleApp()

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

        lines = []
        data = base64.b64encode(open(tfname, "rb").read())
        while data:
            part = data[:72]
            data = data[72:]
            output = '    "%s"' % part
            if not data:
                output += ")"
            lines.append(output)
        data = "\n".join(lines)
    finally:
        if os.path.exists(tfname):
            os.remove(tfname)

    old_index = []
    if catalog and append and python_file != '-':
        # check to see if catalog exists already (file may have been created
        # with an earlier version of img2py or without -c option)
        pyPath, pyFile = os.path.split(python_file)

        append_catalog = True

        sourcePy = open(python_file, "r")
        try:
            for line in sourcePy:

                if line == "catalog = {}\n":
                    append_catalog = False
                else:
                    lineMatcher = indexPattern.match(line)
                    if lineMatcher:
                        old_index.append(lineMatcher.groups()[0])
        finally:
            sourcePy.close()

        if append_catalog:
            out = open(python_file, "a")
            try:
                out.write(
                    "\n# ***************** Catalog starts here *******************"
                )
                out.write("\n\ncatalog = {}\n")
                out.write("index = []\n\n")
            finally:
                out.close()

    if python_file == '-':
        out = sys.stdout
    elif append:
        out = open(python_file, "a")
    else:
        out = open(python_file, "w")

    try:
        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 name of image and/or catalog entry." % imgName

        out.write("#" + "-" * 70 + "\n")
        if not append:
            out.write("# This file was generated by %s\n#\n" % sys.argv[0])
            out.write("from wx.lib.embeddedimage import PyEmbeddedImage\n\n")
            if catalog:
                out.write("catalog = {}\n")
                out.write("index = []\n\n")

        letters = []
        for letter in imgName:
            if not letter.isalnum():
                letter = "_"
            letters.append(letter)
        if not letters[0].isalpha() and letters[0] != '_':
            letters.insert(0, "_")
        varName = "".join(letters)

        out.write("%s = PyEmbeddedImage(\n%s\n" % (varName, data))

        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'] = %s\n" % (imgName, varName))

        if functionCompatibile:
            out.write("get%sData = %s.GetData\n" % (varName, varName))
            out.write("get%sImage = %s.GetImage\n" % (varName, varName))
            out.write("get%sBitmap = %s.GetBitmap\n" % (varName, varName))
            if icon:
                out.write("get%sIcon = %s.GetIcon\n" % (varName, varName))

        out.write("\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)
    finally:
        if python_file != '-':
            out.close()
Пример #7
0
def main(args):
    if not args or ("-h" in args):
        print __doc__
        return

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

    try:
        opts, fileArgs = getopt.getopt(args, "auin: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

    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.BITMAP_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")

    out.write("#" + "-" * 70 + "\n")
    if not append:
        out.write("# This file was generated by %s\n#\n" % sys.argv[0])
        out.write("try:\n")
        out.write("   from gamera.gui import compat_wx\n")
        out.write("   wxImageFromStream = compat_wx.create_image_from_stream\n")
        out.write("   wxBitmapFromImage = compat_wx.create_bitmap_from_image\n")
        out.write("except Exception:\n")
        out.write("   from wxPython.wx import wxImageFromStream, wxBitmapFromImage\n")
        if compressed:
            out.write("import cStringIO, zlib\n\n\n")
        else:
            out.write("import cStringIO\n\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 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)
Пример #8
0
def main(args):
    if not args or ("-h" in args):
        print(__doc__)
        return

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

    try:
        opts, fileArgs = getopt.getopt(args, "auin: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

    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.BITMAP_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")

    out.write("#" + "-" * 70 + "\n")
    if not append:
        out.write("# This file was generated by %s\n#\n" % sys.argv[0])
        out.write("try:\n")
        out.write("   from gamera.gui import compat_wx\n")
        out.write(
            "   wxImageFromStream = compat_wx.create_image_from_stream\n")
        out.write(
            "   wxBitmapFromImage = compat_wx.create_bitmap_from_image\n")
        out.write("except Exception:\n")
        out.write(
            "   from wxPython.wx import wxImageFromStream, wxBitmapFromImage\n"
        )
        if compressed:
            out.write("import cStringIO, zlib\n\n\n")
        else:
            out.write("import cStringIO\n\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 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))
Пример #9
0
def main(args):
    if not args or ("-h" in args):
        print __doc__
        return

    # some bitmap related things need to have a wxApp initialized...
    if wx.GetApp() is None:
        app = wx.PySimpleApp()

    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.BITMAP_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 wx import ImageFromStream, BitmapFromImage\n")
        if icon:
            out.write("from wx import EmptyIcon\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 BitmapFromImage(get%sImage())\n\n"
              "def get%sImage():\n"
              "    stream = cStringIO.StringIO(get%sData())\n"
              "    return ImageFromStream(stream)\n\n" % tuple([imgName] * 4))
    if icon:
        out.write("def get%sIcon():\n"
                  "    icon = EmptyIcon()\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)
Пример #10
0
def img2py(image_file,
           python_file,
           append=DEFAULT_APPEND,
           compressed=DEFAULT_COMPRESSED,
           maskClr=DEFAULT_MASKCLR,
           imgName=DEFAULT_IMGNAME,
           icon=DEFAULT_ICON,
           catalog=DEFAULT_CATALOG):
    """
    Converts an image file to a data structure written in a Python file
    --image_file: string; the path of the source image file
    --python_file: string; the path of the destination python file
    --other arguments: they are equivalent to the command-line arguments
    """
    global app
    if not wx.GetApp():
        app = wx.PySimpleApp()

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

        data = open(tfname, "rb").read()
        data = crunch_data(data, compressed)
    finally:
        if os.path.exists(tfname):
            os.remove(tfname)

    old_index = []
    if catalog and append:
        # check to see if catalog exists already (file may have been created
        # with an earlier version of img2py or without -c option)
        pyPath, pyFile = os.path.split(python_file)

        append_catalog = True

        sourcePy = open(python_file, "r")
        try:
            for line in sourcePy:

                if line == "catalog = {}\n":
                    append_catalog = False
                else:
                    lineMatcher = indexPattern.match(line)
                    if lineMatcher:
                        old_index.append(lineMatcher.groups()[0])
        finally:
            sourcePy.close()

        if append_catalog:
            out = open(python_file, "a")
            try:
                out.write(
                    "\n# ***************** Catalog starts here *******************"
                )
                out.write("\n\ncatalog = {}\n")
                out.write("index = []\n\n")
                out.write("class ImageClass: pass\n\n")
            finally:
                out.close()

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

    try:
        if catalog:
            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

        out.write("#" + "-" * 70 + "\n")
        if not append:
            out.write("# This file was generated by %s\n#\n" % sys.argv[0])
            out.write(
                "from wx import ImageFromStream, BitmapFromImage, EmptyIcon\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 BitmapFromImage(get%sImage())\n\n"
                  "def get%sImage():\n"
                  "    stream = cStringIO.StringIO(get%sData())\n"
                  "    return ImageFromStream(stream)\n\n" %
                  tuple([imgName] * 4))
        if icon:
            out.write("def get%sIcon():\n"
                      "    icon = EmptyIcon()\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)
    finally:
        out.close()