I am writing a GH script in Python (Rino 8). The task is to make a screenshot of a given size from a named view. It seems to work, but after saving the file, the Grasshopper canvas freezes and only responds to scrolling and pressing the push button. If I press the button a second time, it unfreezes and works fine.
the script is follow:
import rhinoscriptsyntax as rs
import scriptcontext as sc
import Rhino
import os
import base64
def capture_view_to_file(file_name, width, height, scale):
old_doc = sc.doc
sc.doc = Rhino.RhinoDoc.ActiveDoc
try:
# Formulating common options for the capture view command
common_options = " _Width={w} _Height={h}".format(w=int(width), h=int(height))
common_options += " _Scale={s}".format(s=scale)
common_options += " _DrawGrid=_No _DrawWorldAxes=_No _DrawCPlaneAxes=_No"
transp = '_Yes'
cmd = '-_ViewCaptureToFile'
cmd += common_options
cmd += " _TransparentBackground={t}".format(t=transp)
cmd += ' "{f}"'.format(f=file_name)
cmd += " _Enter"
# Redrawing the view before executing the command
rs.Redraw()
# Executing the capture view command
success = rs.Command(cmd, echo=False)
if not success:
print("Error capturing PNG image.")
return False
else:
print(f"Image saved successfully at {file_name}")
return True
except Exception as e:
print(f"An error occurred: {e}")
return False
finally:
# Restoring the original document context
sc.doc = old_doc
sc.doc.Views.Redraw()
def save_as_base64(file_path):
try:
with open(file_path, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
base64_file_path = f"{file_path}.base64"
with open(base64_file_path, "w") as base64_file:
base64_file.write(encoded_string)
print(f"Base64 image saved successfully at {base64_file_path}")
except Exception as e:
print(f"An error occurred while encoding to Base64: {e}")
# Getting input data from Grasshopper
capture = capture # capture - input component in Grasshopper
folder = folder # folder - input component in Grasshopper
name = name # name - input component in Grasshopper
width = width_picture # width_picture - input component in Grasshopper
height = heigh_picture # heigh_picture - input component in Grasshopper
scale = scale__picture # scale__picture - input component in Grasshopper
named_view_index = int(named_views) # named_views - input component in Grasshopper
if capture:
# Forming the file path
file_path = os.path.join(folder, f"{name}.png")
sc.doc = Rhino.RhinoDoc.ActiveDoc
# Getting the list of named views
named_views = rs.NamedViews()
if named_view_index < 0 or named_view_index >= len(named_views):
print("Invalid named view index")
else:
# Selecting the desired view
named_view = named_views[named_view_index]
rs.RestoreNamedView(named_view)
rs.CurrentView(named_view)
print(f"Restored and set current view: {named_view}")
# Capturing the view
if capture_view_to_file(file_path, width, height, scale):
# Saving as Base64
save_as_base64(file_path)
sc.doc = ghdoc
sc.doc.Views.Redraw()