Download image and set it as texture of sprite (SOLVED)

Hello guys. I would like download image from server and then set it as texture of sprite. Download image from server is pretty easy, here is part of code:

	http.request(url, "GET", function(self, id, res)
	if res.status ~= 200 and res.status ~= 304 then
		print("Unable to get image", res.response)
		return
	end

	local img = image.load(res.response)
	if not img then
		print("Unable to load image")
		return
	end

The problem is that i do not know what to do next. I have tried something like this:

resource.set_texture( go.get("#sprite", "texture0"), some header, img.buffer ) 

but img.buffer is in string format. So my question is that is there some easy workaround to download image from server and set it as texture of sprite?
Thanks

1 Like

This is probably what you are looking for:

3 Likes

Thank you @britzl, but unfortunately i have already tried this extension without success. Maybe i just srewed up so i will adress next questions to creator of extension. Thanks a lot :slight_smile:

What kind of problems did you run into? Did it crash? Did you get any errors in the console? Share the code that used!

Hi. Here is the code:

local function load_and_set_texture(url)
    http.request(url, "GET", function(self, id, res)
	if res.status ~= 200 and res.status ~= 304 then
		print("Unable to get image", res.response)
		return
	end

	local img = image.load(res.response)
	if not img then
		print("Unable to load image")
		return
	end

	local img_resource = imageloader.load{data = img.buffer}

	pprint(img_resource)
	
	resource.set_texture( go.get("#sprite", "texture0"), img_resource.header, img_resource.buffer )
    end)
end

The problem is that line

imageloader.load{data = img.buffer}

return

DEBUG:SCRIPT: 
{ --[[0000027F34426190]]
header = { --[[0000027F344261E0]]
num_mip_maps = 1,
width = 0,
channels = 0,
height = 0,
type = 3553
}}

As you can see there is no buffer in table and what is fishy that also width and height equal zero.

What if you save the response to disk and then load it instead of loading the response directly?

You should not use image.load() and imageloader.load()! Try:

local img_resource = imageloader.load{data = res.response}
1 Like

Wow @britzl that worked like a charm. Thank you for fast reply. If anyone have hard time with this problem here is the final code of function that works:

local function load_and_set_texture(url)
    http.request(url, "GET", function(self, id, res)
	if res.status ~= 200 and res.status ~= 304 then
		print("Unable to get image", res.response)
		return
	end

	local img_resource = imageloader.load{data = res.response}
	resource.set_texture( go.get("#sprite", "texture0"), img_resource.header, img_resource.buffer )
    end)
end
3 Likes