当前位置: 首页 > 工具软件 > svg2png > 使用案例 >

使用python批量将svg转换成PNG

梁晋鹏
2023-12-01

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]
                input

Convert SVG files to other formats

positional 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 os

inputFolder = "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":#确保是svg
			pngFile = 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":  # 确保是svg
                    pngFile = 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 button

    def 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_box

    def create_files_table(self):
        self._files_table = QTextEdit()
        self._files_table.setReadOnly(True)



if __name__ == '__main__':

    import sys

    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec())


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

参考:

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

下载

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

 类似资料: