Zig
Zig
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 Zig Downloads
const std = @import("std");
const chilkat = @import("chilkat");
pub fn main(init: std.process.Init) !void {
const alloc = init.arena.allocator();
const sb = try chilkat.StringBuilder.init();
defer sb.deinit();
const bd = try chilkat.BinData.init();
defer bd.deinit();
const sb_filename = try chilkat.StringBuilder.init();
defer sb_filename.deinit();
var index: i32 = 1;
try sb.loadFile("qa_data/html/oresp body.txt", "utf-8");
// Assume success.
std.debug.print("length = {d}\n", .{sb.getLength()});
var may_have_more: bool = true;
while (may_have_more) {
// Get the base64 between the 1st occurrence "data:image/png;base64," and "'"
const s_base64 = try sb.getBetween(alloc, "data:image/png;base64,", "'");
// If nothing is found, then we'll exit the loop because there are no more.
may_have_more = sb.getLastMethodSuccess();
if (sb.getLastMethodSuccess()) {
// Found something.
// Load into bd and save.
try bd.loadEncoded(s_base64, "base64");
sb_filename.setString("qa_output/png_") catch {};
sb_filename.appendInt(index) catch {};
sb_filename.append(".png") catch {};
bd.writeFile(try sb_filename.getAsString(alloc)) catch {};
// Replace "data:image/png;base64" with "data:image-png;base64" so the next iteration finds the next occurrence.
sb.replaceFirst("data:image/png;base64", "data:image-png;base64") catch {};
}
index = index + 1;
}
// Restore our replacements..
_ = sb.replace("data:image-png;base64", "data:image/png;base64");
std.debug.print("All done.\n", .{});
}