Inkscape升级至1.2.2后SVG转PNG代码失效,生成文件损坏
SVG转PNG代码在Inkscape 1.2.2版本失效的解决方案
原代码在Inkscape 0.92.1版本可正常将SVG转为PNG并返回,但升级至1.2.2版本后生成的PNG文件损坏,无法打开。问题根源是Inkscape 1.x系列重构了命令行参数,旧版参数已被废弃。
修改后的兼容代码
svgchart = chart_pygal.render() # 适配Inkscape 1.x的命令行参数 inkscape_process = subprocess.Popen( ['inkscape', '--export-type=png', '--export-fd=1', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL ) png_data, error = inkscape_process.communicate(input=svgchart) png_io = BytesIO(png_data) return send_file( png_io, mimetype='image/png', download_name=f"{image_name}.png", as_attachment=True )
参数修改说明
- 移除旧版的
-z参数:Inkscape 1.x在无GUI环境下默认后台运行,无需手动指定 - 替换
-e参数为--export-type=png和--export-fd=1:--export-type=png指定导出格式为PNG--export-fd=1表示将导出内容输出到标准输出(stdout),对应代码中的stdout=subprocess.PIPE
- 保留
-参数:表示从标准输入(stdin)读取SVG内容
可选扩展参数
如果需要自定义导出尺寸,可添加--export-width和--export-height参数,示例:
['inkscape', '--export-type=png', '--export-fd=1', '--export-width=1000', '--export-height=600', '-']
内容的提问来源于stack exchange,提问作者Faizan Naeem
相关产品推荐
相关产品推荐

