Sample code for 30+ languages & platforms
Zig Requires Chilkat v11.7.0+

Fit a QR Code within a Maximum Size

See more QR Code Examples

Demonstrates limiting the size of the image. render.maxWidth and render.maxHeight are the largest image allowed. With render.sizing set to shrinkToFit, QrCode starts from the module size asked for and reduces it, a whole pixel at a time, until the image fits, but never below render.minModuleSize. If it cannot fit, the call fails with noFit rather than returning a code too small to scan.

Chilkat Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    // This example requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    const json = try chilkat.JsonObject.init();
    defer json.deinit();
    json.updateString("payload.text", "https://www.chilkatsoft.com/barcode_overview.asp") catch {};

    // Ask for 10-pixel modules, but accept anything down to 3 pixels to stay within 300 x 300.
    json.updateInt("render.moduleSize", 10) catch {};
    json.updateString("render.sizing", "shrinkToFit") catch {};
    json.updateInt("render.minModuleSize", 3) catch {};
    json.updateInt("render.maxWidth", 300) catch {};
    json.updateInt("render.maxHeight", 300) catch {};

    json.updateString("output.path", "qa_output/qr_fit_300.png") catch {};
    json.updateBool("output.overwrite", true) catch {};
    json.updateString("output.return", "none") catch {};

    const fmt = try chilkat.Formats.init();
    defer fmt.deinit();
    const json_out = try chilkat.JsonObject.init();
    defer json_out.deinit();
    fmt.qrCode("generate", json, json_out) catch {
        std.debug.print("{s}\n", .{try fmt.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("module asked for: {s} pixels\n", .{try json_out.stringOf(alloc, "measurements[0].requestedPitch")});
    std.debug.print("module used: {d} pixels\n", .{json_out.intOf("measurements[0].pitch")});
    std.debug.print("image: {d} x {d} pixels\n", .{ json_out.intOf("measurements[0].canvasWidth"), json_out.intOf("measurements[0].canvasHeight") });

    // The image written to qa_output/qr_fit_300.png:

    // image

    // The same code cannot fit in 100 x 100 with modules of at least 3 pixels.
    json.updateInt("render.maxWidth", 100) catch {};
    json.updateInt("render.maxHeight", 100) catch {};
    fmt.qrCode("generate", json, json_out) catch {
        std.debug.print("100 x 100: {s} ({s})\n", .{ try json_out.stringOf(alloc, "errors[0].code"), try json_out.stringOf(alloc, "errors[0].message") });
    };

    // Sample output:

    // module asked for: 10 pixels
    // module used: 7 pixels
    // image: 287 x 287 pixels
    // 100 x 100: noFit (the symbol does not fit the render constraints: minModuleSize)
}