preview_utils.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import os
  2. import matplotlib
  3. matplotlib.use('Agg')
  4. import matplotlib.pyplot as plt
  5. from stl import mesh
  6. from mpl_toolkits import mplot3d
  7. def generate_stl_preview(stl_path: str, output_path: str):
  8. """
  9. Generates a PNG preview image for an STL file.
  10. """
  11. try:
  12. # Load the STL file
  13. your_mesh = mesh.Mesh.from_file(stl_path)
  14. # Create a new plot
  15. figure = plt.figure(figsize=(8, 8))
  16. # Use transparent background for a premium look
  17. figure.patch.set_alpha(0.0)
  18. axes = figure.add_subplot(111, projection='3d')
  19. axes.set_facecolor((0,0,0,0)) # Transparent background inside plot
  20. # Add the mesh to the plot
  21. poly = mplot3d.art3d.Poly3DCollection(your_mesh.vectors)
  22. # Professional-looking blue/gray color
  23. poly.set_facecolor([0.2, 0.5, 0.8, 0.9])
  24. poly.set_edgecolor([0.1, 0.1, 0.1, 0.2])
  25. axes.add_collection3d(poly)
  26. # Auto-scale the plot
  27. scale = your_mesh.points.flatten()
  28. axes.auto_scale_xyz(scale, scale, scale)
  29. # Hide axes for a clean look
  30. axes.set_axis_off()
  31. # Adjust view for better perspective
  32. axes.view_init(elev=30, azim=45)
  33. # Save the result
  34. plt.savefig(output_path, dpi=100, bbox_inches='tight', transparent=True)
  35. plt.close(figure)
  36. return True
  37. except Exception as e:
  38. print(f"Error generating preview: {e}")
  39. return False