How to load image from buffer without knowing the file type

Godot Version

4.4 beta 1

Question

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?

if you’re using windows(11) go to the file manager, click at the 3 dots

Schermafbeelding 2025-02-16 220806

click at view(im currently using another language :frowning: )

and click to “filename extensions” so it gets a check( turned on )

now, you will be able to see if a file is a png or jpg :slight_smile: and sorry because i was using another language :frowning:

I’m fetching an image from the Web. It can be a png, jpg, svg, or whatever. I need to be able to tell in code which loading function to use

You could try reading the file signature, sorry I’m not sure if there is a better/easier way already built in to do that.

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)

2 Likes

I don’t think there is a Image.load_from_buffer?

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.

1 Like

This sounds promising. If there isn’t a built in way I’ll try looking for the signatures

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
image

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.