CairoSVG介绍

CairoSVG是一个将SVG转为PNG,PDF, PS格式的库,当前版本的CairoSVG至少需要Python 3.5以上版本。

CairoSVG安装和使用

pip install cairosvg

通过命令行你就可以使用CairoSVG,以下代码能够将当前目录下的image.svg文件转换为image.png文件:

cairosvg image.svg -o image.png

命令参数

cairosvg --help
usage: cairosvg [-h] [-v] [-f {pdf,png,ps,svg}] [-d DPI] [-W WIDTH][-H HEIGHT] [-s SCALE] [-u] [--output-width OUTPUT_WIDTH][--output-height OUTPUT_HEIGHT] [-o OUTPUT]inputConvert SVG files to other formatspositional arguments:input                 input filename or URL 文件名或者url链接名optional arguments:-h, --help            show this help message and exit 帮助-v, --version         show program's version number and exit 版本查看-f {pdf,png,ps,svg}   --format {pdf,png,ps,svg} output format 输出格式                      -d DPI, --dpi DPI     ratio between 1 inch and 1 pixel 输出图像dpi比率设置 DPI比率介于1英寸和1像素之间-W WIDTH, --width WIDTH    width of the parent container in pixels 输入图像宽-H HEIGHT, --height HEIGHT  height of the parent container in pixels 输入图像高-s SCALE, --scale SCALE    output scaling factor 输出图像缩放比例-u, --unsafe          resolve XML entities and allow very large files 解析XML实体(WARNING: vulnerable to XXE attacks and various DoS) 但是有安全问题--output-width OUTPUT_WIDTH     desired output width in pixels 期望图像输出宽--output-height OUTPUT_HEIGHT   desired output height in pixels 期望图像输出高-o OUTPUT, --output OUTPUT     output filename 图像输出名

使用Python转换

https://doc.qt.io/qtforpython-6

import cairosvg
import osinputFolder = "D:/tool/fritzing.0.9.4.64.pc_and_dll/fritzing.0.9.4.64.pc/fritzing-parts/svg/core/breadboard"    #输入的文件夹,里面有svg
outputFolder = "D:/Temp/output"  #输出的文件夹,将把结果放到此文件夹中for root, dirs, files in os.walk(inputFolder):#遍历所有的文件for f in files:svgFile = os.path.join(root,f)  #svg文件名if f[-3:] == "svg":#确保是svgpngFile = outputFolder + "/" + f.replace("svg","png") #png文件名try: cairosvg.svg2png(url=svgFile, write_to=pngFile, dpi=1900)except:print('error =>' + pngFile)finally:print('file => ' + pngFile)

封装成可操作的界面

"""PySide6 port of the linechart example from Qt v6.x"""import os
import cairosvg
from PySide6.QtCore import (QCoreApplication, QDir, QFile, QFileInfo,QIODevice, QTextStream, QUrl, Qt)
from PySide6.QtGui import QDesktopServices
from PySide6.QtWidgets import (QAbstractItemView, QApplication, QComboBox,QDialog, QFileDialog, QGridLayout, QHBoxLayout,QHeaderView, QLabel, QLineEdit,QPushButton, QSizePolicy, QTableWidget,QTableWidgetItem, QVBoxLayout, QWidget, QTextEdit)# os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = 'D:\software\Anaconda3\Lib\site-packages\PySide6\plugins\platforms'class Window(QDialog):def __init__(self, parent=None):super().__init__(parent)# 输入选择directory_label = QLabel("选择文件夹:")self._directory_combo_box = self.create_combo_box(QDir.currentPath())self._browse_button = self.create_button("&打开...", self.browse)# 输出选择output_directory_label = QLabel("输出到的文件夹:")self._output_directory_combo_box = self.create_combo_box(QDir.currentPath())self._output_browse_button = self.create_button("&选择...", self.output_browse)self._find_button = self.create_button("&转换", self.convert_svg2png)self.create_files_table()buttons_layout = QHBoxLayout()buttons_layout.addStretch()buttons_layout.addWidget(self._find_button)main_layout = QGridLayout()main_layout.addWidget(directory_label, 0, 0)main_layout.addWidget(self._directory_combo_box, 0, 1)main_layout.addWidget(self._browse_button, 0, 2)main_layout.addWidget(output_directory_label, 2, 0)main_layout.addWidget(self._output_directory_combo_box, 2, 1)main_layout.addWidget(self._output_browse_button, 2, 2)main_layout.addWidget(self._files_table, 3, 0, 1, 3)main_layout.addLayout(buttons_layout, 5, 0, 1, 3)self.setLayout(main_layout)self.setWindowTitle("将svg转换成png")self.resize(500, 300)def browse(self):self.directory = QFileDialog.getExistingDirectory(self, "转换",QDir.currentPath())if self.directory:if self._directory_combo_box.findText(self.directory) == -1:self._directory_combo_box.addItem(self.directory)self._directory_combo_box.setCurrentIndex(self._directory_combo_box.findText(self.directory))def output_browse(self):self.output_directory = QFileDialog.getExistingDirectory(self, "输出到",QDir.currentPath())if self.output_directory:if self._directory_combo_box.findText(self.output_directory) == -1:self._directory_combo_box.addItem(self.output_directory)self._directory_combo_box.setCurrentIndex(self._directory_combo_box.findText(self.output_directory))def convert_svg2png(self):for root, dirs, files in os.walk(self.directory):  # 遍历所有的文件for f in files:svgFile = os.path.join(root, f)  # svg文件名if f[-3:] == "svg":  # 确保是svgpngFile = self.output_directory + "/" + f.replace("svg", "png")  # png文件名try:cairosvg.svg2png(url=svgFile, write_to=pngFile, dpi=1900)except:self._files_table.append('error =>' + pngFile)print('error =>' + pngFile)finally:self._files_table.append('file => ' + pngFile)print('file => ' + pngFile)def create_button(self, text, member):button = QPushButton(text)button.clicked.connect(member)return buttondef create_combo_box(self, text=""):combo_box = QComboBox()combo_box.setEditable(True)combo_box.addItem(text)combo_box.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Preferred)return combo_boxdef create_files_table(self):self._files_table = QTextEdit()self._files_table.setReadOnly(True)if __name__ == '__main__':import sysapp = QApplication(sys.argv)window = Window()window.show()sys.exit(app.exec())

如果想选择单个文件或者是转换成不同的格式,可以自己添加。

参考:

[python] CairoSVG使用教程_落痕的寒假的博客-CSDN博客_cairosvg python

下载

svg2pngqt转换-桌面系统文档类资源-CSDN文库

使用python批量将svg转换成PNG相关推荐

  1. 使用Python批量将PDF转换成图片

    引用自 https://zhuanlan.zhihu.com/p/307990818. import os import time import fitz #以下为批量PDF转图片的代码 pdf_fi ...

  2. python读取一个TXT转换成EXCEL表格

    [任务]:python读取一个TXT转换成EXCEL表格 [坑1]pycharm安装后代码区不能编辑,是由于最新的pycharm在安装时自动装了vimVim插件, 方法一:在tools-Vim emu ...

  3. 用Python将word文件转换成html(转)

    用Python将word文件转换成html 序 最近公司一个客户大大购买了一堆医疗健康方面的科普文章,希望能放到我们正在开发的健康档案管理软件上.客户大大说,要智能推送!要掌握节奏!要深度学习!要让用 ...

  4. python word处理_妙用Python将word文件转换成html 方法超简单

    什么方法可以将word文件转换成html,找了一圈,没有发现合适的应用可以把word或indd转化成干净的html.机缘巧合,无意间听说python很擅长文本处理,用Python将word文件转换成h ...

  5. Python:UTF-8编码转换成GBK编码

    2019独角兽企业重金招聘Python工程师标准>>> #!/usr/bin/env python # -*- coding:utf-8 -*- #UTF-8转换成GBK编码 #te ...

  6. 如何批量将word转换成excel表格

    平时我们工作总会接触很多的文档,转换文档格式也总是很多文件一起,不借助第三方工具的话只能一个个手动转换,非常浪费时间,为了解救大家,小编在这里分享可以批量转换的方法. 转换前的准备:批量将word转换 ...

  7. win下海康工业相机使用python读取视频并转换成cv格式

    硬件设备:海康威视工业相机CA013-A0UC USB3 环境:win10,python3.7,海康MVS 海康工业相机环境配置(MVS) 配置好环境后可以运行一下MVS和MVS\Developmen ...

  8. 如何批量将图片转换成jpg格式?

    如何批量将图片转换成jpg格式?很多小伙伴都想这道这个问题的答案,有些PS高手可以通过PS软件实现批量转换,但是这个方法对于普通人来说比登天还难,学习如何PS就要耗费很多的时间,如果你是一名上班族,领 ...

  9. python 人像素描_基于python实现把图片转换成素描

    这篇文章主要介绍了基于python实现把图片转换成素描,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 导语: 你是否还在为当时年少时没有选择自己的梦 ...

最新文章

  1. nginx环境的搭建
  2. iOS下JS与OC互相调用(五)--UIWebView + WebViewJavascriptBridge
  3. 微生物分类学研究利器:模式微生物基因组数据库
  4. python代码架构_Python架构
  5. Vue+Openlayer使用Draw实现交互式绘制线段
  6. 拷贝文件不移动_在不使用 mv 命令的情况下移动文件
  7. 【嵌入式】Libmodbus源码分析(一)-类型和结构体
  8. 自动化测试工具selenium使用介绍
  9. linux没有interface文件,Linux下interface文件修改
  10. Web缓存相关知识整理
  11. windows安装pip包
  12. 21SkypeForBusiness2015进阶篇--SFB后端Mirror切换到AllwaysOn--标准版准备篇
  13. devc语言图形编程教程_devc编程软件程序怎么调试 devc调试步骤图文方法教程
  14. ArcGIS 安装出现Mircrosoft .NET Framework 3.5 sp1问题的解决方案
  15. ROS中的物体识别——ORK功能包的使用
  16. MDT2012配置无人职守安装
  17. 锐捷 linux 网卡信息失败,linux折腾日记:校园网锐捷上网设置
  18. 2022/8/8测试总结
  19. 计算机的音频管理器在哪里打开,Realtek高清晰音频管理器怎么找不到打开教程...
  20. SAP License:公司上一套sap系统得多少钱?

热门文章

  1. 不会盗QQ,还当程序员吗
  2. 2023年系统分析师论文真题
  3. Go内核源码剖析 一 程序执行启动过程
  4. 近9成盗版Office用户称愿投奔开源(转)
  5. python分析数据包_Python解析pcap数据包
  6. 1066:护卫队 (动态规划)
  7. VS2019 VC++ MFC CEF(Chrome)开发环境搭建及相关功能demo(附源码)
  8. Ubuntu20.04安装RMF组件
  9. 【Python】Python 中sqrt函数求负数的平方根
  10. 文心一格小程序,AI绘画产品