将二进制的stl文件转换为ascii的形式
总会遇到可多软件导出的stl是二进制形式,导致不能修改;自己写个程序转换下,以防后续使用没办法转化;
1.具体程序如下:
import sys
import vtk
import os
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QLineEdit, QTextEdit, QFileDialogdef convert_stl_to_ascii(input_stl_path, output_stl_path):# 读取 STL 文件reader = vtk.vtkSTLReader()reader.SetFileName(input_stl_path)reader.Update()# 获取读取的数据polydata = reader.GetOutput()# 创建 STL 写入器writer = vtk.vtkSTLWriter()writer.SetFileName(output_stl_path)writer.SetInputData(polydata)writer.SetFileTypeToASCII()# 写入文件writer.Write()# 处理文件第一行,将其替换为 solid + 文件名file_name_without_ext = os.path.splitext(os.path.basename(input_stl_path))[0]new_first_line = f'solid {file_name_without_ext}'with open(output_stl_path, 'r+') as f:lines = f.readlines()if lines:lines[0] = new_first_line + '\n'f.seek(0)f.writelines(lines)f.truncate()def batch_convert_stl_files(input_folder, status_text):output_folder = f"{input_folder}_output"if not os.path.exists(output_folder):os.makedirs(output_folder)for root, _, files in os.walk(input_folder):for file in files:if file.lower().endswith('.stl'):input_file_path = os.path.join(root, file)output_file_name = os.path.splitext(file)[0] + ".stl"output_file_path = os.path.join(output_folder, output_file_name)convert_stl_to_ascii(input_file_path, output_file_path)status_text.append(f"已将 {input_file_path} 转换为 ASCII 格式的 {output_file_path}")class STLConverterApp(QWidget):def __init__(self):super().__init__()self.initUI()def initUI(self):layout = QVBoxLayout()# 选择文件夹按钮self.select_button = QPushButton("选择文件夹")self.select_button.clicked.connect(self.select_folder)layout.addWidget(self.select_button)# 文件夹路径输入框self.folder_entry = QLineEdit()layout.addWidget(self.folder_entry)# 开始转换按钮self.start_button = QPushButton("开始转换")self.start_button.clicked.connect(self.start_conversion)layout.addWidget(self.start_button)# 状态文本框self.status_text = QTextEdit()self.status_text.setReadOnly(True)layout.addWidget(self.status_text)self.setLayout(layout)self.setWindowTitle("STL 文件批量转换工具")self.setGeometry(300, 300, 600, 400)def select_folder(self):folder = QFileDialog.getExistingDirectory(self, "选择文件夹")if folder:self.folder_entry.setText(folder)def start_conversion(self):input_folder = self.folder_entry.text()if input_folder:batch_convert_stl_files(input_folder, self.status_text)if __name__ == '__main__':app = QApplication(sys.argv)window = STLConverterApp()window.show()sys.exit(app.exec())
2.打包
打包命令如下:
C:\Users\xxx\.conda\envs\py310\Scripts\pyinstaller.exe --add-data="C:\Users\zpp\.conda\envs\py310\Library\bin\ffi-8.dll;." -F -w pyside6.py