Topic was automatically imported from the old Question2Answer platform.
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 = ImageTexture.new()
var img = Image
onready var imag = get_node("Sprite")
if Input.is_action_just_pressed("ui_home"):
img = load($FileDialog.selected)
tex.create_from_image(img)
imag.set_texture(tex)
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!
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.
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
projects.
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.
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.