
from BaseDataMaintenance.common.swf.export import SVGExporter

from BaseDataMaintenance.common.swf.movie import SWF
import re
import codecs
import base64
import os
import io

def swf2images(filepath,export_dir):

    if not os.path.exists(export_dir):
        os.mkdir(export_dir)
    if type(filepath)==io.BytesIO:
        swf_file = SWF(filepath)
        svg_exporter = SVGExporter()
        svg = swf_file.export(svg_exporter)
    else:
        with open(filepath, 'rb') as f:
            swf_file = SWF(f)
            svg_exporter = SVGExporter()
            svg = swf_file.export(svg_exporter)
            # with open('swf_export.jpg', 'wb') as f:
            #     f.write(svg.read())
    swf_str = str(svg.getvalue(), encoding='utf-8')

    # print(swf_str)
    # 正则匹配图片的信息位置
    result0 = re.finditer('<image id=(.[^>]*)', swf_str)
    image_bytes_list = []
    i = 0
    image_path_list = []
    for r in result0:
        i += 1
        # 截取图片信息所在位置
        swf_str0 = swf_str[r.span()[0]:r.span()[1]+1]

        # 正则匹配得到图片的base64编码
        result1 = re.search('xlink:href="data:(.[^>]*)', swf_str0)
        swf_str1 = swf_str0[result1.span()[0]:result1.span()[1]]
        reg1_prefix = 'b\''
        result1 = re.search(reg1_prefix + '(.[^\']*)', swf_str1)
        swf_str1 = swf_str1[result1.span()[0]+len(reg1_prefix):result1.span()[1]]

        # base64_str -> base64_bytes -> no "\\" base64_bytes -> bytes -> image
        base64_bytes_with_double = bytes(swf_str1, "utf-8")
        base64_bytes = codecs.escape_decode(base64_bytes_with_double, "hex-escape")[0]
        image_bytes = base64.b64decode(base64_bytes)
        image_bytes_list.append(image_bytes)
        image_path = os.path.join(export_dir,"swf_page_%d.png"%(i))
        with open(image_path, 'wb') as f:
            f.write(image_bytes)

if __name__=="__main__":
    swf2images("F:\\Workspace2016\\BaseDataMaintenance\\BaseDataMaintenance\\maintenance\\attachment\\fixdownload\\1632033929300.swf","swf_files")
    # print(os.listdir(os.path.join(os.path.dirname(__file__),"swf_files")))