I’m using io
APIs to read/write external image cache for textures. It’s working well on Android but getting an error ERROR:DLIB: Failed to load image: 'Corrupt JPEG'
on Windows. My guess is that the f:read("*a")
doesn’t return full file content on Windows.
Here is my code:
local M = {}
local save_dir = html5 and "KyHoang_Download" or "KyHoang/Download"
local cached = {}
function M.from_external(link, callback)
if cached[link] then
local img = cached[link]
gui.new_texture(link, img.width, img.height, img.type, img.buffer)
callback(link)
else
local make_texture_from_local_path = function(local_path)
local f = io.open(local_path, "r")
if f then
local data = f:read("*a")
local img = image.load(data)
gui.new_texture(link, img.width, img.height, img.type, img.buffer)
cached[link] = img
callback(link)
io.close(f)
end
end
local filename = link:gsub("[%p%c%s]", "")
local path = sys.get_save_file(save_dir, filename)
local f = io.open(path, "r")
if f then
io.close(f)
make_texture_from_local_path(path)
else
http.request(link, "GET", function(_self, id, response)
if response.status == 200 or response.status == 304 then
f = io.open(path, "w+")
if f then
f:write(response.response)
io.close(f)
end
make_texture_from_local_path(path)
end
end)
end
end
end
return M