How To Load Runtime-Generated Image File Inside RichTextLabel

Godot Version

4.4.1

Question

I am working on a project in which I want to download images from a server / API and then display the resulting image (.png) inside a RichTextLabel using the [img] BBCode.

Currently I download the file, write the buffer to a file in a folder used to store them temporary files (Temporary as in only for each time the app is launched) and then load said image to then set the line to something like this;

line = "[img]{" + image_path + "}[/img]"

This returns an error as;
Resource file not found {"*image path which does exist as I have a FileAccess.file_exists() before this code*"} {expected type: Texture2D}
I also tried saving the buffer to an Image and then referencing that Images resource path, and get the same thing.
(I am aware Texture2D does not inherit from Image but it’s the only thing I could think of to load an Image-type resource in code from a runtime value)

My question is; how can I make the RichTextLabel recognise the newly-downloaded image so that it can be loaded and displayed to the user, as it seems writing it to a file or saving it to a resource results in it failing to recognise the file despite it being verifiably-existent.

Thanks.

The [img] tag will only load Resources saved with ResourceSaver.save() files saved with any other method aren’t considered Resources and [img] won’t be able to load them.

You can instead use RichTextLabel.add_image() and RichTextLabel.update_image() to add and update a Texture2D without needing to save the file to disk.

extends Node


@onready var rich_text_label: RichTextLabel = $RichTextLabel
@onready var http_request: HTTPRequest = $HTTPRequest


func _ready() -> void:
	http_request.request_completed.connect(_on_request_completed)

	http_request.request("https://picsum.photos/64/64")


func _on_request_completed(result: int, response_code: int, headers: PackedStringArray, body: PackedByteArray):
	if not result == OK:
		return

	if not response_code == 200:
		return

	var img = Image.create_empty(64, 64, false, Image.FORMAT_RGBA8)
	img.load_jpg_from_buffer(body)
	var tex = ImageTexture.create_from_image(img)
	
	# Save the ImageTexture as a Resource inside the user:// folder
	ResourceSaver.save(tex, 'user://img.res')
	rich_text_label.text = "[img]user://img.res[/img] hello world"

	# Alternatively, use the ImageTexture directly without saving it
	rich_text_label.add_image(tex)
	rich_text_label.add_text(" hello world")
1 Like

Thank you!

I wasn’t aware about add_image() and its related methods for the RichTextLabel, made some slight changes and it started working;
It makes much more sense now, I had assumed they wanted a file path from the file system opposed to a resource path so it makes sense since the images weren’t saved as resources it wasn’t finding them.