How to convert Image to Texture?

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

Want to achieve something like a photo album, showing pictures not in the assets folder, but elsewhere on the HD of a user. Loading a texture directly with:

get_node("../TextureRect").texture = load(imgFile)

gives an Error like “No loader found” if say a “.png” file is outside the asset folder. I can load this “external” file into an Image object without error, but I found no way to convert this Image to a texture and assign that texture, like so:

func _on_Button_pressed():
	var imgFile = "F:/pictures/" + fileList[imgNumber]
	imgNumber += 1
	var img = Image.new()
	img.load(imgFile)
	get_node("../TextureRect").texture.set_data(img)

Before I set the texture of the “TextureRect” to an “ImageTexture” with size 640 x 360. With this there always is an error like:

“Condition ‘!texture->active’ = true”

Cannot figure out what I am doing wrong.

1 Like
:bust_in_silhouette: Reply From: Artium Nihamkin

Try to create a texture from that image and set it instead (don’t use set_data).

Thank you so much. This one works:

func _on_Button_pressed():
	var imgFile = "F:/pictures/" + fileList[imgNumber]
	imgNumber += 1
	
	var img = Image.new()
	var itex = ImageTexture.new()
	img.load(imgFile)
	itex.create_from_image(img)
	get_node("../TextureRect").texture = itex

Maxpilot | 2018-02-12 18:20

This does not work in android. I am getting black screen.

supper_raptor | 2020-03-20 10:08

Update for Godot4. Posting here since it was the first result on Google and it may be helpful to others.

The function create_from_image is now static, meaning you do not need to create the itex object in the code by Maxpilot.

The second half of the function can now be written as:

var img = Image.new()
img.load(imgFile)
get_node("../TextureRect").texture = ImageTexture.create_from_image(img)

afiefh | 2023-04-15 18:53

3 Likes

That’s great!
In C# you can use ImageTexture.CreateFromImage(image)