Skip to content

Instantly share code, notes, and snippets.

@JanHolger
Created November 5, 2022 14:27
Show Gist options
  • Save JanHolger/f39a3195de1334baf41dadd1da505d40 to your computer and use it in GitHub Desktop.
Save JanHolger/f39a3195de1334baf41dadd1da505d40 to your computer and use it in GitHub Desktop.
Downloads a file from a given url and converts it into a data url
function base64Encode(data)
local function encodeChar(n)
if n <= 25 then
return string.char(65 + n)
end
if n <= 51 then
return string.char(97 + n - 26)
end
if n <= 61 then
return string.char(48 + n - 52)
end
if n == 62 then
return "+"
end
return "/"
end
if type(data) == "string" then
local newData = {}
for i=1,string.len(data) do
table.insert(newData, data:sub(i, i))
end
data = newData
end
local res = ""
local pos = 1
while pos <= #data do
local c1 = string.byte(data[pos])
local c2 = 0
if pos + 1 <= #data then
c2 = string.byte(data[pos + 1])
end
local c3 = 0
if pos + 2 <= #data then
c3 = string.byte(data[pos + 2])
end
res = res .. encodeChar(c1 >> 2) .. encodeChar(((c1 & 3) << 4) | (c2 >> 4))
if pos + 1 <= #data then
res = res .. encodeChar(((c2 & 15) << 2) | (c3 >> 6))
if pos + 2 <= #data then
res = res .. encodeChar(c3 & 63)
else
res = res .. "="
end
else
res = res .. "=="
end
pos = pos + 3
end
return res
end
function downloadFile(url)
local tmpFile = "tmp-" .. tostring(math.random(1000,9999))
local h = io.popen("curl -is --output " .. tmpFile .. " " .. url)
h:close()
h = io.open(tmpFile, "rb")
local t = ""
local l = h:read("*l")
while l ~= "\r" do
if l:sub(1, 13):lower() == "content-type:" then
t = l:sub(15, l:len() - 1)
end
l = h:read("*l")
end
local data = h:read("*a")
h:close()
os.remove(tmpFile)
return {
type = t,
data = data
}
end
function urlToBase64DataUrl(url)
local file = downloadFile(url)
return "data:" .. file.type .. ";base64," .. base64Encode(file.data)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment