Skip to content

Instantly share code, notes, and snippets.

@ale2x72
Forked from jotson/screenshot.gd
Last active January 6, 2024 18:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ale2x72/01ad8191f49015627104913b45ded311 to your computer and use it in GitHub Desktop.
Save ale2x72/01ad8191f49015627104913b45ded311 to your computer and use it in GitHub Desktop.
Godot GDScript screenshot function
# This is a function for capturing screenshots with GDScript
# from: https://gist.github.com/jotson/84681c2064653d093083a690e9fa5998
# Adapted for Godot4.2.1 by ale2x72
func screenshot():
# Capture the screenshot
var image = get_viewport().get_texture().get_image()
# Setup path and screenshot filename
var date = Time.get_datetime_dict_from_system()
# save in a subfolder of the executable file
var path = OS.get_executable_path().get_base_dir().path_join("screenshots")
# var path = "user://screenshots" # replace above line with this to save in the user:// path
# string formatting corrected for Windows
var file_name = "screenshot_%d%02d%02d_%02d.%02d.%02d" % [date.year, date.month, date.day, date.hour, date.minute, date.second]
if not DirAccess.dir_exists_absolute(path):
DirAccess.make_dir_absolute(path)
var dir = DirAccess.open(path)
# Find a filename that isn't taken
var n = 1
var file_path = path.path_join(file_name) + ".png"
while(true):
if dir.file_exists(file_path):
file_path = path.path_join(file_name) + "-" + str(n) + ".png"
n = n + 1
else:
break
# for debugging purposes only
# print("Screenshot saved in ", ProjectSettings.globalize_path(path))
# Save the screenshot
image.save_png(file_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment