PNG到SVG Python

2024-10-04 05:22:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用Python将PNG图像转换成SVG,但当我运行这段代码时,输出的图像甚至无法在Photoshop或浏览器中加载。我做错什么了?在

    import os
    import base64
    startSvgTag = """<?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
    "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
    <svg version="1.1"
    xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    width="240px" height="240px" viewBox="0 0 240 240">"""

    endSvgTag = """</svg>"""
    for files in os.listdir("."):
        if files.endswith(".png"):
            pngFile = open(files, 'rb')
            base64data = base64.b64encode(pngFile.read()).replace(b'\n',b'')
            base64String = '<image xlink:href="data:image/png;base64,{0}" width="240" height="240" x="0" y="0" />'.format(base64data)
            f = open(os.path.splitext(files)[0]+".svg",'w')
            f.write( startSvgTag + base64String + endSvgTag)
            print('Converted ',files,' to ',os.path.splitext(files)[0],".svg")

Tags: svgorg图像importhttposversionwww
1条回答
网友
1楼 · 发布于 2024-10-04 05:22:44

如果您只想修复代码,请删除.replace(b'\n',b''),并将.format(base64data)更改为.format(base64data.decode('utf-8'))。在

如果base64data是IVBoR32==,那么在python3中将其表示为b'IVBoR32=='。执行.format(base64data)时,image元素变成<image xlink:href="data:image/png;base64,b'IVBoR32=='" width="240" height="240" x="0" y="0" />,这是不正确的。基本上,您需要将base64数据转换为str,然后再转换为format。在

相关问题 更多 >