forked from alesan99/mari0_ae
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathonlineimage.lua
51 lines (44 loc) · 1.35 KB
/
onlineimage.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
require("utils")
softloadhttps()
require("love.image")
require("love.filesystem")
require("love.graphics")
require("love.data")
local input = love.thread.getChannel("image_input")
local output = love.thread.getChannel("image_output")
---@type table<string, love.ImageData>
local cache = {}
--- Downloads an image to an ImageData object.
---@param url string The URL of the image.
---@return love.ImageData|nil image The image data.
local function createImageData(url)
local code, body = https.request(url)
if code ~= 200 or not body then return nil end
local success, bytedata = pcall(love.data.newByteData, body)
if not success then return nil end
local success, imagedata = pcall(love.image.newImageData, bytedata)
if not success then return nil end
-- note: love.graphics.newImage does not work in threads
return imagedata
end
while true do
local asset = input:demand()
if asset == "stop" then
--stop the thread
break
elseif asset then
--load image
local url = asset.icon_url
if cache[url] then
output:supply({"img", url, cache[url]})
return
end
local image = createImageData(url)
if image then
cache[url] = image
output:supply({"img", url, image})
else
output:supply({"error"})
end
end
end