How to import an image file and set it as a texture while in-game

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

Basically I want to import an image file and set it as a sprite/texture for an object while the game runs.

I just started coding so my code is a mess yet I will show you what I came up with.

I used a file dialog to select the file I wanted:

var selected = null

func _process(_delta):

if visible:

selected = get_current_path()

And then I tried to import the file I selected with load function and set it as a texture:

var tex =
var img = Image

onready var imag = get_node("Sprite")
    if Input.is_action_just_pressed("ui_home"):
        img = load($FileDialog.selected)

But the thing is this only works for files within res:// folder. I can’t import a file from a different directory which isn’t already imported as a texture in godot editor. Help appreciated. Thanks!

:bust_in_silhouette: Reply From: BVictor

it’s simpler than it looks. you need to define the location of the image that you will change in game. then when you set a texture the texture will be the variable. like:

var sword_texture = load("res://assets/icons/sword.png")

and when you want change the texture you will load the variable like a texture.

$TextureRect.texture = sword_texture
:bust_in_silhouette: Reply From: yrtv

You can’t use load outside of res:// and user://.
From Image — Godot Engine (stable) documentation in English

Warning: This method should only be used in the editor or in cases
when you need to load external images at run-time, such as images
located at the user:// directory, and may not work in exported

Use format specific methods load_png_from_buffer, load_jpg_from_buffer (see linked page for more methods)

“used in cases when you need to load external images at run-time” is exactly what’s being requested. user:// directory is mentioned just as an example of a location outside of res:// and the warning about possibly not working in exported projects is probably about html5 games not having access to the filesystem.

Maunomau | 2022-01-12 00:58

:bust_in_silhouette: Reply From: miremrie

This is the same answer I gave on this question:

I’ve had success with this code loading .png in Godot 4.0 stable.
There is an example in docs for ImageTexture

var image = Image.load_from_file(path)
var texture = ImageTexture.create_from_image(image)
brush.texture = texture

Here, path is an absolute path received by FileDialog picker, with file in the desktop folder, brush is a Sprite2D
Tried on Windows 10. Seems to work in exported project also.