如何将PyVista PolyData写入流或内存缓冲区?
问题描述
基于FastAPI搭建服务器,接收GemPy模型后生成3D模型,从中提取地层为PyVista/VTK PolyData对象的流程运行正常,但需要将这些对象转换为.glb/.vtk/.ply等客户端可用格式并返回时,无法通过pyvista.PolyData.save()或VTK Writer将文件保存到内存缓冲区。
基础代码如下:
# 生成可提取地层polydata的对象 gpv = gp.plot_3d(geo_model) # 获取polydata或非结构化网格的示例 poly = gpv.surface_poly['Sandstone_2'] grid = pv.UnstructuredGrid(poly)
尝试过的两种方式均失败:
- PyVista直接保存:仅能写入本地文件,无法写入内存缓冲区
poly.save("filename.ply") - VTK写入缓冲区:传入
BytesIO对象时抛出错误TypeError: SetFileName argument %Id: %Vdef write_grid_to_vtk(grid, filename): writer = vtk.vtkUnstructuredGridWriter() writer.SetFileName(filename) writer.SetInputData(grid) #writer.SetFileTypeToBinary() writer.Write() buf = io.BytesIO() write_grid_to_vtk(grid, buf) buf.close()
解决方案
方法1:PyVista直接写入内存缓冲区(推荐)
PyVista的save方法原生支持写入BytesIO对象,无需本地文件操作,示例代码:
import io import pyvista as pv from fastapi import Response # 假设已获取目标PolyData对象poly buf = io.BytesIO() # 指定保存格式,支持ply/vtk/glb等 poly.save(buf, file_format="ply") buf.seek(0) # 重置缓冲区指针至起始位置 # 在FastAPI中返回文件 return Response( content=buf.getvalue(), media_type="application/octet-stream", headers={"Content-Disposition": "attachment; filename=Sandstone_2.ply"} )
可通过pv.core.utilities.file_formats.get_supported_formats()查看PyVista支持的所有格式
方法2:VTK内存流写入
VTK普通Writer仅接受文件名,需使用VTK内置的内存流组件实现写入,示例以VTK XML格式为例:
import io import vtk from fastapi import Response def write_grid_to_memory(grid): # 对应格式选择Writer,如写PLY用vtk.vtkPLYWriter writer = vtk.vtkXMLUnstructuredGridWriter() writer.SetInputData(grid) # 创建VTK内存输出流 output_stream = vtk.vtkBufferOutputStream() writer.SetOutputStream(output_stream) writer.Write() # 转换为Python字节数据 buffer = output_stream.GetBuffer() return bytes(buffer) # 使用示例 grid_bytes = write_grid_to_memory(grid) buf = io.BytesIO(grid_bytes) buf.seek(0) # FastAPI返回文件 return Response( content=buf.getvalue(), media_type="application/octet-stream", headers={"Content-Disposition": "attachment; filename=Sandstone_2.vtu"} )
内容的提问来源于stack exchange,提问作者j_kaden
相关产品推荐
相关产品推荐

