Load texture from file and assign to texture

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

Let’s say i have a sprite and i want to load a texture with the path C:/test.png and assign it to the sprite.

Normally to assign a texture to a sprite via the editor you just load it and it’s assigned to the sprite with a StreamTexture that has a .stex file.

I’m not sure how that all works, is there a simpler way to load a texture from a given file path into a sprite? StreamTexture seems like the only subclass of texture that’s designed for handling loading textures from file, but i can’t figure out how to make it work.

StreamTexture.LoadPath seems to reference the path of a .stex file, not sure how it works if you don’t have a .stex file though.

:bust_in_silhouette: Reply From: Zylann

To load a texture from a file located inside your project, this is the preferred way:

texture = load("res://path/to/your/texture.png")

To load a texture from a file located anywhere on the filesystem, provided your game has the access rights:

var image = Image.new()
var err = image.load("path/to/the/image.png")
if err != OK:
    # Failed
texture = ImageTexture.new()
texture.create_from_image(image, 0)

Note that this second way will not have gone through import, so any extra options need to be specified manually. It should be preferred for savegames or images provided by the player.

Please how do I turn off the filter on this one? I wanna import pixel art images

wamiqurrehman | 2020-04-08 11:08

On which one? Loading from game resources or loading from user’s filesystem?

Zylann | 2020-04-08 13:16

load() method returns “Resource” which is a base class of “ImageTexture”. why both the methods are same ?

bob333 | 2020-06-17 19:17

bob333: load written alone is a function, not a method (technically, it’s a shorthand for ResourceLoader.load()). Image.load() on the other hand is a method of Image. They are not the same. One loads a resource, the other loads an image from a file.

Zylann | 2020-06-17 19:27

@zylann: I should have been clearer. Why is the return type of “ResourceLoader.load()” considered as ImageTexture (ie. the first type in the post) ?

bob333 | 2020-06-17 19:49

bob333: it will probably be a StreamTexture actually. That happens because ResourceLoader.load() returns the imported resource type from the path you provide. Images are imported by default as StreamTexture. If you want it to return an Image, you should configure that file to be imported as Image.

Zylann | 2020-06-17 20:12