FANDOM


The following is a script Penguin-Pal and I wrote in Python 3.4 that can be used as an alternative to his quick drop if rescaling SWFs is slow or laggy on your browser.

In order to use it, you first need to have Python 3.x and SWiX installed on your computer.

Instructions

  1. Open SWiX and open the SWF file you would like to rescale
  2. Go to File > Save As... and save it as an XML file
  3. Search for "IDLE (Python GUI)" on your computer, open it, and go to File > New File
  4. Copy the code below and paste it into the new file window
  5. Save it in the same folder as the SWF file
  6. Go to Run > Run Module and it will let you rescale the XML file (see here for common values for rescaling)
  7. Open the rescaled XML file in SWiX
  8. Click the Play button and check if it looks how you want it to (if it doesn't, run the script again and keep making adjustments on the original XML file)
  9. Go to File > Save As... and save it as an SWF file
  10. You're done - you can now move on to whatever you were planning to do with the SWF, such as rendering it to a PNG image using Kurst SWF Renderer

  1. Open SWiX and open the SWF file
  2. Go to File > Save As... and save it as an XML file
  3. Make sure the script is in the same folder as the SWF file you would like to rescale
  4. Run the script through whatever IDE you use or simply through your command prompt (see here for common values for rescaling)
  5. Open the rescaled XML file in SWiX
  6. Click the Play button and check if it looks how you want it to (if it doesn't, run the script again and keep making adjustments on the original XML file)
  7. Go to File > Save As... and save it as an SWF file
  8. You're done - you can now move on to whatever you were planning to do with the SWF, such as rendering it to a PNG image using Kurst SWF Renderer

Code

'''
    |#| scale up SWF files from SWiX markup
    |#| by Penguin-Pal, Hey.youcp and Vicyorus
    |#| June 29, 2015 / August 16, 2015
'''
 
### imports ###
 
import re     #regex
 
 
### set global data ###
data = {}
 
 
### functions ###
 
# read file
def getFile():
    data["fileName"] = input("Please specify the XML filename (in the same folder, without the filetype): ")
    data["fileFound"] = False
    try:
        data["file"] = open(data["fileName"] + ".xml", "r")
        data["fileFound"] = True
    except FileNotFoundError:
        print("Error: file could not be found!")
 
 
# set global data modifications
def setData():
 
    shiftXLoop = True
    while shiftXLoop:
        data["shiftX"] = input("Please pick your X-axis shifting (0 for no changes): ")
        try:
            data["shiftX"] = int(data["shiftX"])
            shiftXLoop = False
        except ValueError:
            print("Error: invalid input!")
 
    shiftYLoop = True
    while shiftYLoop:
        data["shiftY"] = input("Please pick your Y-axis shifting (0 for no changes): ")
        try:
            data["shiftY"] = int(data["shiftY"])
            shiftYLoop = False
        except ValueError:
            print("Error: invalid input!")
 
    scaleLoop = True
    while scaleLoop:
        data["scale"] = input("Please pick your scaling value (1 for no changes): ")
        try:
            data["scale"] = float(data["scale"])
            scaleLoop = False
        except ValueError:
            print("Error: invalid input!")
 
    windowLoop = True
    while windowLoop:
        data["window"] = input("Please pick new window dimensions (width=height, n for no changes): ").lower()
        if data["window"] == "n":
            windowLoop = False
        else:
            try:
                data["window"] = int(data["window"])
                windowLoop = False
            except ValueError:
                print("Error: invalid input!")
 
# read file content
def getFileContent(cb):
    content = data.get("file").read()
    data["file"].close()
    cb(content)
 
 
# parse file
def editFile(content):
    # set local variables, for an easier access
    output = content
    scale = data["scale"]
    shiftX = data["shiftX"]
    shiftY = data["shiftY"]
    window = data["window"]
 
    # set new window size
    if window != "n":
        output = re.sub(' Width="\d*"', ' Width="' + str(window) + '"', output, count=1)
        output = re.sub(' Height="\d*"', ' Height="' + str(window) + '"', output, count=1)
 
    # update all 'Movie > PlaceObject2' selector-like occurrences
    regex = re.compile('\n {4}<PlaceObject2(?: [^\n]*)>\n(?: {5,}[^\n]*\n)* {4}<\/PlaceObject2>')
    matches = re.findall(regex, output) # all matches
    fragments = re.split(regex, output) # split the full file content at matches
    tempContent = "" # temporary content
    while len(matches) > 0:
        tempContent += editMatrixParent(matches.pop(0), scale, shiftX, shiftY) + fragments.pop(1)
    output = fragments[0] + tempContent # join first fragment + temp content
 
    # update glow effects based on scaling
    output = updateGlow(output)
 
    # now save file
    saveFile(output)
 
# save file
def saveFile(newContent):
    file = open(data["fileName"] + "_rescaled.xml", "w")
    file.write(newContent)
    file.close()
    print("Done! Look for a file named " + data["fileName"] + "_rescaled.xml in your folder.")
 
# modify a 'PlaceObject2' text representation
def editMatrixParent(s, scale, shiftX, shiftY):
    if s.find("\n        <Matrix>") == -1:
        # missing <Matrix>
        temp = s.split("\n")
        temp[0] += '        <Matrix>\n            <Scale ScaleX="' + str(scale) + '" ScaleX="' + str(scale) + '" />\n            <Translate TranslateX="' + str(shiftX * scale) + '" TranslateY="' + str(shiftY * scale) + '" />\n        </Matrix>'
        s = "\n".join(temp)
    else:
        # has <Matrix>, but make sure that sub elements exist
        matrix = s.split("\n") # matrix area
        hasScale = False
        hasTransform = False
        temp = [] # temporary output
        for line in matrix:
            if line.find("<Scale") == 12:
                # line with <Scale>
                hasScale = True
                ScaleX = float(re.findall('ScaleX="(.+?)"', line)[0]) * scale
                ScaleY = float(re.findall('ScaleY="(.+?)"', line)[0]) * scale
                temp.append('<Scale ScaleX="' + str(ScaleX) + '" ScaleY="' + str(ScaleY) + '" />')
                continue
            elif line.find("<Translate") == 12:
                # line with <Translate>
                hasTransform = True
                TranslateX = (float(re.findall('TranslateX="(.+?)"', line)[0]) + shiftX) * scale
                TranslateY = (float(re.findall('TranslateY="(.+?)"', line)[0]) + shiftY) * scale
                temp.append(removeFloat('<Translate TranslateX="' + str(TranslateX) + '" TranslateY="' + str(TranslateY) + '" />'))
                continue
            elif line.find("<Rotate") == 12:
                # line with <Rotate>
                RotateSkew0 = float(re.findall('RotateSkew0="(.+?)"', line)[0]) * scale
                RotateSkew1 = float(re.findall('RotateSkew1="(.+?)"', line)[0]) * scale
                temp.append('<Rotate RotateSkew0="' + str(RotateSkew0) + '" RotateSkew1="' + str(RotateSkew1) + '" />')
                continue
            elif line.find("</Matrix>") == 8 and not(hasScale and hasTransform):
                # end of matrix, but Translate and/or Scale are missing
                closing = ""
                if not(hasScale):
                    closing += '<Scale ScaleX="' + str(scale) + '" ScaleY="' + str(scale) + '" />\n'
                if not(hasTransform):
                    # another note for <Translate> - if it ends with '.0', the fraction part must be removed
                    closing += removeFloat('<Translate TranslateX="' + str(shiftX * scale) + '" TranslateY="' + str(shiftY + scale) + '" />\n')
                temp.append(closing + line)
                del closing
                continue
            else:
                # other
                temp.append(line)
        s = "\n".join(temp)
    # return final value
    return s
 
# change glow effect based on scaling value
def updateGlow(s):
    a = s.split("\n")
    c = []
    for b in a:
        if b.find("<Blur") > -1 and b.find("<BlurFilter>") == -1:
            # blur node
            nodeName = "BlurX"
            scale = int(data["scale"])
            if b.find("<BlurY") > -1:
                nodeName = "BlurY"
            High = float(re.findall('High="(.+?)"', b)[0]) * scale
            Low = float(re.findall('Low="(.+?)"', b)[0]) * scale
            c.append(removeFloat('<' + nodeName + ' High="' + str(High) + '" Low="' + str(Low) + '" />'))
        else:
            # no blur - append as is
            c.append(b)
    return "\n".join(c)
 
# remove the decimal point and what comes after it for numeric attributes that end with ".0"
# this is needed for attributes of <Transform> and <Blur>
def removeFloat(s):
    return s.replace(".0\"", "\"")
 
# main
def main():
    mainLoop = True
    while mainLoop:
        getFile()
        if data["fileFound"]:
            setData()
            getFileContent(editFile)
            anotherLoop = True
            while anotherLoop:
                data["another"] = input("Rescale another file? (y/n): ").lower()
                if data["another"] == "y":
                    anotherLoop = False
                elif data["another"] == "n":
                    anotherLoop = False
                    mainLoop = False
                else:
                    print("Error: invalid input!")
        else:
            tryAgainLoop = True
            while tryAgainLoop:
                data["tryAgain"] = input("Try again? (y/n): ").lower()
                if data["tryAgain"] == "y":
                    tryAgainLoop = False
                elif data["tryAgain"] == "n":
                    tryAgainLoop = False
                    mainLoop = False
                else:
                    print("Error: invalid input!")
 
 
### implementation ###
 
if __name__ == "__main__":
    main()
Community content is available under CC-BY-SA unless otherwise noted.