Search code examples
godotgdscriptgodot4

Take screenshots in Godot 4.1 Stable


=I'm trying to make a screenshot function for my game. I want it to save the current view to a jpg file when a button is pressed I have successfully made the tracking of clicking the save screenshot button, but the save screenshot function doesn't work

Tracking the pressing of the screenshot button

func _physics_process(delta):
    ...

    if Input.is_action_pressed("TAKE SCREENSHOT"): 
        take_screenshot()

Screenshot function

func take_screenshot(): # Function for taking screenshots and saving them
    
    var screenshot_path = "user://" + "screenshot_" + Time.get_date_string_from_system() + "_" + Time.get_time_string_from_system() + ".jpg" # the path for our screenshot.

    var image = get_viewport().get_texture().get_image() # We get what our player sees
    
    image.flip_y() 
    image.save_jpg(screenshot_path)

I get this error

E 0:00:05:0395   player.gd:2030 @ take_screenshot(): Can't save JPG at path: 'user://screenshot_2023-12-01_18:24:09.jpg'.
  <Ошибка C++>   Condition "err" is true. Returning: err
  <Исходный код C++>modules/jpg/image_loader_jpegd.cpp:193 @ _jpgd_save_func()
  <Трассировка стека>player.gd:2030 @ take_screenshot()
                 player.gd:587 @ _physics_process()

Solution

  • The problem is that there are unallowed characters in the file name. You are not allowed to use ":" on windows at least. So you should alter the date and time strings to make sure there are no unallowed characters:

    func take_screenshot(): # Function for taking screenshots and saving them
        
        var date = Time.get_date_string_from_system().replace(".","_") 
        var time :String = Time.get_time_string_from_system().replace(":","")
        var screenshot_path = "user://" + "screenshot_" + date+ "_" + time + ".jpg" # the path for our screenshot.
    
        var image = get_viewport().get_texture().get_image() # We get what our player sees
        
        image.save_jpg(screenshot_path)
    

    I also replace any "." in the date. Although these are not invalid, they are normally used for file extensions.

    Edit: Not sure, if you really need the flip_y. Was your screenshot upside down? Edit2: I also removed image.flip_y() from the code. As Silvio Mayolo pointed out: This is not necessary anymore in Godot 4. The screenshot is not rendered upside down anymore