Creating a WEBP in memory from network data (Image class)

Godot Version

v4.4.1.stable.steam [49a5bc7b6]

Question

I have a two ways of loading an image, through network (this is what i want), and a saved copy on local disk.
Loading image from file with Image class loads it perfectly, but attempt to create in from raw file data does not succeed (fetching data via internet gives raw file data, same as reading it from disc, so in the example, instead of fetching url, i read file from disc)
I want to fetch data from network and create image in game with Image class, but something goes wrong.

My code


@export_file("*.webp") var file_path
@export var url : String = "" # irrelevant in this example

func work():
	var file_access = FileAccess.open(file_path, FileAccess.READ)
	
	# same data that i will get from http request
	var data = file_access.get_buffer(file_access.get_length())
	
	var image_from_file = Image.load_from_file(file_path) # success
	var temp = Image.create_from_data(
		image_from_file.get_width(), # i know by the fact that it is 512
		# but i'll use get_width() and get_height()
		image_from_file.get_height(),
		image_from_file.has_mipmaps(), # does not use mipmaps but i'll use method
		image_from_file.get_format(), # format is 5 (i believe it's Image.FORMAT_RGBA8
		image_from_file.get_data(),
	) # ALMOST THE SAME AS LOADING IMAGE FROM FILE
	
	var image_from_data = Image.create_from_data(
		512, 512,
		false, Image.FORMAT_RGBA8,
		data
	) # Expected Image data size of 512x512x4 (RGBA8 without mipmaps) = 1048576 bytes,
	  # got 29962 bytes instead.
	# FAIL
	# I need to load an image from THIS data that i will fetch online,
	# without creating even temporary file
	# how do i do this?
	# what do i did wrong?

When i create image by loading it from file, it’s data size is larger than raw file data, i think this is because raw data is compressed or something, but how do i decompress or whatever it’s data by hand?
I dont want to create temporary files on disc each time i download an image file

This topic is about webp files, but if you know how to handle other formats, please let me know

Solution

var image = Image.new()
var error = image.load_webp_from_buffer(data)
if error != OK:
 push_error(error_string(error))
 return

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