Sample code for 30+ languages & platforms
Lua 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 Lua Downloads

Lua
local chilkat = require("chilkat")

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

local json = chilkat.JsonObject.new()
json:update_string("payload.text", "https://www.chilkatsoft.com/barcode_overview.asp")

-- Ask for 10-pixel modules, but accept anything down to 3 pixels to stay within 300 x 300.
json:update_int("render.moduleSize", 10)
json:update_string("render.sizing", "shrinkToFit")
json:update_int("render.minModuleSize", 3)
json:update_int("render.maxWidth", 300)
json:update_int("render.maxHeight", 300)

json:update_string("output.path", "qa_output/qr_fit_300.png")
json:update_bool("output.overwrite", true)
json:update_string("output.return", "none")

local fmt = chilkat.Formats.new()
local jsonOut = chilkat.JsonObject.new()
local success = fmt:qr_code("generate", json, jsonOut)
if not success then
    print(fmt.last_error_text)
    return
end

print("module asked for: " .. jsonOut:string_of("measurements[0].requestedPitch") .. " pixels")
print("module used: " .. jsonOut:int_of("measurements[0].pitch") .. " pixels")
print("image: " .. jsonOut:int_of("measurements[0].canvasWidth") .. " x " .. jsonOut:int_of("measurements[0].canvasHeight") .. " pixels")

-- 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:update_int("render.maxWidth", 100)
json:update_int("render.maxHeight", 100)
success = fmt:qr_code("generate", json, jsonOut)
if not success then
    print("100 x 100: " .. jsonOut:string_of("errors[0].code") .. " (" .. jsonOut:string_of("errors[0].message") .. ")")
end

-- 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)