The image class has a bunch of methods for loading images from buffer, like load_png_from_buffer or load_jpg_from_buffer. But I am loading images from the web, and I don’t know the file type beforehand. How can I handle this?
In Godot, when loading images from a buffer but the file type is unknown, you can use Image.load_from_buffer(), which automatically detects the image format and loads it correctly.
Here’s how you can do it:
var http_request = HTTPRequest.new()
func _ready():
add_child(http_request)
http_request.request_completed.connect(_on_request_completed)
http_request.request("https://example.com/image")
func _on_request_completed(result, response_code, headers, body):
if result == HTTPRequest.RESULT_SUCCESS:
var image = Image.new()
var err = image.load_from_buffer(body)
if err == OK:
var texture = ImageTexture.create_from_image(image)
# Use the texture as needed
else:
print("Failed to load image from buffer")
else:
print("Failed to fetch image, response code:", response_code)
An alternative to parsing the signature could be reading the Content-Type header to get the file-type. However, this somewhat depends on where you get the image from and if the content-type header is correctly sent.
Ok I think checking the first few bytes for the signature is the right path. I looked into the source code for the asset library and saw they do that too, with these signatures