Loading a external image if it exists as Sprite2D texture on program start

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Meister_Li

Hello there! :slight_smile:

I have Sprite2D node that I use to hold the background image of my app. I would like users to be able to place a custom image in the png format in the user folder (in this case, C:\Users<user>\AppData\Roaming\Godot\app_userdata<App_Name>), that then gets loaded and used, should it exist.

I have the following code set up for it, but unfortunately, image is always just “blank” in the game after it has started. If the file doesn’t exist, the already set texture loads correctly.

extends Sprite2D

func _init():
	var custom_texture = load_png("user://battlefield.png")
	if custom_texture != null:
		set_texture(custom_texture)

func load_png(file):
	var png_file = File.new()
	if png_file.file_exists(file):
		var img = Image.new()
		var data = img.load(file)
		var imgtex = ImageTexture.new()
		imgtex.create_from_image(img)
		png_file.close()
		return imgtex
	else:
		return null

Thank you for your help! :slight_smile:

Hmmm… Generally, that looks reasonable I think. A few thoughts…

You probably want to check for a load error here (maybe you’re getting an error and don’t know it?).

var err = image.load(file)
if err != OK:
    # fail

Remember, the image doesn’t go through any import options when loading this way, so anything you want there will need to be set manually.

Also, you’re getting the default value (7) for the flags arg on the create_from_image() call. If that’s not what you want, you can pass a bit value into that call.

See here for flag details.

jgodfrey | 2022-09-05 14:32

Thank you for reply - I was able to figure it out with some finnageling. :slight_smile:

func _init():
	var custom_texture = load_png("user://battlefield.png")

func load_png(file):
	var png_file = File.new()
	if png_file.file_exists(file):
		var img = Image.new()
		var err = img.load(file)
		if err != OK:
			print("Image load error")
		var newTexture = ImageTexture.create_from_image(img)
		texture = newTexture

Meister_Li | 2022-09-06 22:16