Save_png won't create files

Godot Version

4.2

Question

I’m trying to save a png file, following tutorials like this one. Everything seems to work except for saving the file itself. I’ve tried saving to user://..., res://..., and hardcoded paths. Nothing creates a file.

Oddly, I am able to save and load files with FileAccess.

Is there some special setting to enable saving of pngs? Am I missing something essential in the png code?

I’m on Mac OS: Ventura 13.4.1, in case that makes any difference.

extends Node2D

func _ready():

	var size = Vector2(32, 32)
	var color = Color.RED
	var png_file = "res://my_image.png"
	# var png_file = "user://my_image.png"
	# var png_file = "/my/absolute/path/my_image.png"

	var img = Image.new()
	img.create(size.x, size.y, false, Image.FORMAT_RGBA8)
	img.fill(color)
	img.save_png(png_file)

	print(png_file)
	print(ProjectSettings.globalize_path(png_file))


	# Save a variable
	var save_path = "user://score.save"
	var file = FileAccess.open(save_path, FileAccess.WRITE)
	file.store_var(10)
	file.close()

	# Load the variable and print it, to prove it worked
	var file2 = FileAccess.open(save_path, FileAccess.READ)
	var score = file2.get_var()
	file2.close()
	print("Score: ", score)

What’s the error message / error code you get? Are you saving to a folder that doesn’t exist (they are not automatically made)

1 Like

Do you have permission to write to the user directory?

I don’t get an error message. The game never crashes or anything—the file just never gets written.

I think so. Otherwise, how would the FileAccess command write to disk?

And you know where the user directory on your computer is?

1 Like

Yes, it’s documented here: File paths in Godot projects — Godot Engine (stable) documentation in English

My script prints it out using this line: print(ProjectSettings.globalize_path(png_file))

I’ve verified that score.save is created there, and my_image.png is not.

Ran your code and got an error message.

E 0:00:00:0371   test.gd:12 @ _ready(): Condition "compressed_size <= png_size_estimate" is true. Returning: FAILED
  <C++ Source>   drivers/png/png_driver_common.cpp:187 @ image_to_png()
  <Stack Trace>  test.gd:12 @ _ready()
E 0:00:00:0371   test.gd:12 @ _ready(): Can't convert image to PNG.
  <C++ Error>    Condition "err" is true. Returning: err
  <C++ Source>   drivers/png/resource_saver_png.cpp:54 @ save_image()
  <Stack Trace>  test.gd:12 @ _ready()

the create function doesn’t modify the original image instance, you need to assign it.

img = img.create(size.x, size.y, false, Image.FORMAT_RGBA8)

idk why you didn’t get an error message though.

1 Like

Thanks for replicating! I’ll give it a shot in my game as soon as I can.