Can you write a script which saves the contents of the currently active view window
to an image file (e.g., PNG, JPG, TIFF) with specified resolution?
from MSPyBentley import * from MSPyECObjects import * from MSPyBentleyGeom import * from MSPyDgnPlatform import * from MSPyDgnView import * from MSPyMstnPlatform import * import os import tkinter as tk from tkinter import filedialog, simpledialog, messagebox def save_active_view_to_image(file_format='PNG', width=1024, height=768): """ Saves the contents of the currently active view window to an image file with specified
resolution and format.
Supported formats: PNG, JPG, TIFF. """ # Get the active view set and selected viewport vSet = IViewManager.GetActiveViewSet() viewport = vSet.GetSelectedViewport() if viewport is None: print("No view selected!") return viewIndex = viewport.GetViewNumber() # Define the image size imageSize = Point2d() imageSize.x = width imageSize.y = height # Map file format string to ImageFileFormat enum fmt = file_format.upper() if fmt == 'PNG': imageFileFormat = ImageFileFormat.eIMAGEFILE_PNG ext = '.png' elif fmt == 'JPG' or fmt == 'JPEG': imageFileFormat = ImageFileFormat.eIMAGEFILE_JPEG ext = '.jpg' elif fmt == 'TIFF': imageFileFormat = ImageFileFormat.eIMAGEFILE_TIFF ext = '.tiff' else: print("Unsupported file format!") return # Prompt user for save location root = tk.Tk() root.withdraw() file_path = filedialog.asksaveasfilename( defaultextension=ext, filetypes=[(f"{fmt} files", f"*{ext}"), ("All files", "*.*")] ) if not file_path: print("Save cancelled.") return # Delete file if it already exists if os.path.exists(file_path): os.remove(file_path) # Save the view screenshot to the image file retVal = MstnImage.saveView(file_path, imageSize, MSRenderMode.eConstantShade, imageFileFormat,
False, False, viewIndex) if BentleyStatus.eSUCCESS == retVal: print(f"Image saved successfully at {file_path}") else: print("Failed to save view screenshot as an image") def main(): root = tk.Tk() root.withdraw() fmt = simpledialog.askstring("Image Format", "Enter image format (PNG, JPG, TIFF):", initialvalue="PNG") if not fmt: print("No format entered. Exiting.") exit() width = simpledialog.askinteger("Width", "Enter image width (pixels):", initialvalue=1024, minvalue=1) height = simpledialog.askinteger("Height", "Enter image height (pixels):", initialvalue=768, minvalue=1) if not width or not height: print("Invalid dimensions. Exiting.") exit() save_active_view_to_image(fmt, width, height) # Example usage: prompt user for format and resolution, then save if __name__ == "__main__": main()
Python: Documentation | API Presentations | FAQs | GitHub | Samples | Wikis | Blogs