Lua
Lua
Extract data:image/png;base64 from HTML
See more Base64 Examples
Demonstrates how to extract base64 image data from HTMl and save to files.Chilkat Lua Downloads
local chilkat = require("chilkat")
local sb = chilkat.StringBuilder.new()
local bd = chilkat.BinData.new()
local sbFilename = chilkat.StringBuilder.new()
local index = 1
local success = sb:load_file("qa_data/html/oresp body.txt", "utf-8")
-- Assume success.
print("length = " .. sb.length)
local mayHaveMore = true
while mayHaveMore do
-- Get the base64 between the 1st occurrence "data:image/png;base64," and "'"
local sBase64 = sb:get_between("data:image/png;base64,", "'")
-- If nothing is found, then we'll exit the loop because there are no more.
mayHaveMore = sb.last_method_success
if sb.last_method_success then
-- Found something.
-- Load into bd and save.
success = bd:load_encoded(sBase64, "base64")
sbFilename:set_string("qa_output/png_")
sbFilename:append_int(index)
sbFilename:append(".png")
bd:write_file(sbFilename:get_as_string())
-- Replace "data:image/png;base64" with "data:image-png;base64" so the next iteration finds the next occurrence.
sb:replace_first("data:image/png;base64", "data:image-png;base64")
end
index = index + 1
end
-- Restore our replacements..
local count = sb:replace("data:image-png;base64", "data:image/png;base64")
print("All done.")