Search code examples
2dgodotgdscriptgodot4

How to create Image and save as jpg in Godot 4.2.2?


Godot 4.2.2 OS: Mac 14.5 (23F79) Chip: Apple M2 Pro

I tried to create image dynamically and save it as .jpg image.

func _ready():
    var user_data_dir = OS.get_user_data_dir()
    print("User data directory:", user_data_dir)

    # Create a new image with specified width, height, and format
    var image = Image.new()
    image.create(256, 256, false, Image.FORMAT_RGB8)  # Creating a 256x256 image with RGB format
    
    # Fill the image with black
    image.fill(Color.BLACK)  # Fill the entire image with black color
    
    # Check if the image is empty (filled it with black); i don't think this is necessary but just checking
    var is_empty = true
    for y in range(image.get_height()):
        for x in range(image.get_width()):
            var pixel_color = image.get_pixel(x, y)
            if pixel_color != Color.TRANSPARENT:  # Check against black color with transparent
                is_empty = false
                break
        if not is_empty:
            break

    if is_empty:
        print("The image is empty.")
    else:
        print("The image is not empty.")

    # Save the image as a JPG file
    var file_path_jpg = user_data_dir + "/black_image2.jpg"
    var result_jpg = image.save_jpg(file_path_jpg)

    if result_jpg == OK:
        print("JPG saved successfully at: ", file_path_jpg)
    else:
        print("Failed to save JPG. Error code: ", str(result_jpg))

    # Verify if the file exists
    var jpg_exists = FileAccess.file_exists(file_path_jpg)
    print("JPG exists: ", str(jpg_exists))
Output Log:
User data directory:/Users/xxxx/Library/Application Support/Godot/app_userdata/game
The image is empty.
Failed to save JPG. Error code: 31
JPG exists: true

even thought file created its empty.

I tried to create an RGB8 image, fill it with color, and save it. But for some reason, the saved file is empty. Any idea why this is happening?

Note: I’ve been learning Godot for the past two weeks after switching from Unity, so if this is a newbie question, please bear with me. Thanks!

I also tried to save the png file it didn't even create the png file but i tried with .jpg it created file but with empty data. All the code i have written is in detail section and output log.

I want to create image, write something in image and save that image that's it.


Solution

  • Haven't tested this myself but I'm 90% sure the issue is this line early on:

    var image = Image.new()
    image.create(256, 256, false, Image.FORMAT_RGB8)
    

    The issue being that Image.create() is a static method that returns image. That means that you should instead be doing:

    var image = Image.create(256, 256, false, Image.FORMAT_RGB8)
    

    The code you have now is assigning everything to an empty "image" variable because Image.create() returns the new image it does not apply it if you call it on an instance the way you have it written