Downloaded images are random noise (SOLVED)

In my project, I have a script that downloads an image and loads it into a sprite component. My code is:

local w = 62
local h = 62
local pixels = https.request(message.data.icon)
print(message.data.icon)
print(pixels)

-- encode
local bytes = png.encode_rgb(pixels, w, h)

-- decode the png to RGBA buffer
local buf, w, h = png.decode_rgba(bytes)

-- change the texture on a sprite to the loaded png
local resource_path = go.get("#icon", "texture0")
local header = { width = w, height = h, type = resource.TEXTURE_TYPE_2D, format = resource.TEXTURE_FORMAT_RGBA, num_mip_maps = 1 }
		resource.set_texture(resource_path, header, buf)

which I copied from britzl’s defold-png examples. This is what it shows:

Original
636185254766574022
Downloaded
Beyond%20The%20Lands

Since someone’s going to ask, here’s the URL to the original image.

http.request() - async method, you have to use callback function (doc)

Also, you don’t need encode response, just decode.

Right code:

	local url = "https://media.forgecdn.net/avatars/thumbnails/82/982/62/62/636185254766574022.png"
	http.request(url, "GET", function(self, id, response)
		local buf, w, h = png.decode_rgba(response.response)
		local resource_path = go.get("#sprite", "texture0")
		local header = { width = w, height = h, type = resource.TEXTURE_TYPE_2D, format = resource.TEXTURE_FORMAT_RGBA, num_mip_maps = 1 }
		resource.set_texture(resource_path, header, buf)
	end)
2 Likes

It works! The only problem is that the GO the script is in is duplicated with a factory. Whenever I build now, the icons quickly scroll through. I believe this is because each instance of the sprite originally uses the same image, so now each time you change one of images, it changes all of them. Also, I always get the error:

ERROR:SCRIPT: /gui/packs/pack.script:33: Wrong type for table attribute 'width'. Expected number, got nil
stack traceback:
	[C]: in function 'set_texture'
	/gui/packs/pack.script:33: in function </gui/packs/pack.script:29>

line 33 being resource.set_texture(resource_path, header, buf).

Are you sure that you need to use sprites for this kind of things?
Your icon looks like GUI element. Did you try to load it for use in GUI components as nodes. There is an example of how to do that: https://www.defold.com/examples/gui/load_texture/

1 Like

No, it’s not a GUI element. I might try to recreate in my GUI.