preview_utils.py 1.4 KB

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