from qgis.core import ( QgsProject, QgsVectorLayer, QgsProcessingFeatureSourceDefinition, QgsProcessing, QgsApplication ) from qgis.analysis import QgsNativeAlgorithms # 初始化 QGIS(适用于独立脚本) # 如果你在 QGIS 自带的 Python 控制台中运行,跳过这部分 QgsApplication.setPrefixPath("/usr", True) qgs = QgsApplication([], False) qgs.initQgis() # 注册原生算法(若未启用) QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) # 加载矢量图层 layer_path = "/path/to/your/input_layer.shp" # 替换为你的输入图层路径 input_layer = QgsVectorLayer(layer_path, "Input Layer", "ogr") if not input_layer.isValid(): print("Failed to load the input layer!") else: print("Input layer loaded successfully!") # 设置缓冲区参数 buffer_distance = 10 # 缓冲区距离(单位取决于图层 CRS) output_path = "/path/to/your/output_buffer.shp" # 替换为输出文件路径 # 调用缓冲区工具 params = { 'INPUT': QgsProcessingFeatureSourceDefinition(input_layer.source(), selectedFeaturesOnly=False), 'DISTANCE': buffer_distance, # 缓冲区距离 'SEGMENTS': 4, # 缓冲区边界平滑度(更多段数更平滑) 'END_CAP_STYLE': 2, # 端点样式:0=圆角,1=平端,2=尖角 'JOIN_STYLE': 2, # 节点连接样式:0=圆角,1=斜接,2=尖角 'MITER_LIMIT': 2, # 斜接限值(仅当 JOIN_STYLE 为斜接时有效) 'DISSOLVE': False, # 是否溶解结果 'OUTPUT': output_path # 输出文件路径 } # 运行缓冲区分析 processing_output = QgsApplication.processingRegistry().algorithmById("native:buffer").run(params) if processing_output['OUTPUT']: print(f"Buffer created successfully: {output_path}") else: print("Buffer creation failed!") # 在 QGIS 中加载输出图层 output_layer = QgsVectorLayer(output_path, "Buffered Layer", "ogr") QgsProject.instance().addMapLayer(output_layer) # 清理(适用于独立脚本) qgs.exitQgis()