Styling & Logo Embedding

GET /v1/qr/generate and POST /v1/qr/generate look like simple parameter sheets, but the visual output is produced by two different renderers depending on format, and logo embedding quietly rewrites one of your parameters. This page covers the render pipeline end to end so branded QR codes scan reliably.

Parameter reference: QR Code Generation. Symbology choice: Symbology Selection.

Base URL

https://barcode.toolkitapi.io

The two renderers

format Engine Honours
png qrcode + Pillow (StyledPilImage) size, module_shape, fg_color, bg_color, error_correction, logo_url/logo, logo_size
svg segno fg_color, bg_color, error_correction — ignored: size, module_shape, logo*

svg output is written with scale=10 and border=4, so a 33-module (version 4) QR renders as (33 + 8) * 10 = 410 px square; the size scales with the QR version, not with size. Passing size=2000 with format=svg returns 200 and an SVG whose width/height reflect the module count — no error, just an ignored parameter. If you need exact pixel dimensions, use PNG.

PNG pipeline, step by step

  1. Colour parse. hex_to_rgb() strips a leading #, expands 3-digit forms (f00 → ff0000), accepts 6 or 8 hex digits, and raises ValueError (→ 400) for anything else. Alpha is accepted but discarded — #ff000080 yields RGB (255,0,0) and the PNG is fully opaque. Transparent QR codes are not supported.
  2. Error-correction override. ec = EC_MAP[error_correction], then if a logo is present, ec is replaced with H regardless of what you asked for. You cannot get a lower EC level together with a logo; the response still has no field telling you it happened.
  3. Matrix build. qrcode.QRCode(error_correction=ec, box_size=10, border=4) + make(fit=True). box_size is irrelevant to output size (the image is resized in step 5) but does affect how the module drawer draws shapes before downscaling.
  4. Module shape. module_shape maps to a drawer class:
Value Drawer Practical effect
square SquareModuleDrawer Best scannability, sharpest edges
rounded RoundedModuleDrawer Soft corners; safe
circle CircleModuleDrawer Dots; visually loses contrast at small sizes
gapped GappedSquareModuleDrawer Shrinks modules; the most fragile option

An unknown shape falls back to square via MODULE_DRAWERS.get(...) — but the query parameter is a Literal, so an unknown value is a 422 before the code runs. 5. Resize. img.resize((size, size), Image.LANCZOS) — always exactly size × size px, square, regardless of module count. Below ~modules × 4 px you are downscaling modules into sub-pixel territory; a 400 px QR with version 10 (57 modules) gives ~7 px per module, which is fine, but a size=100 version-10 code gives ~1.7 px and will blur. 6. Logo. If logo_url or a base64 logo (POST only) supplied an image: - logo_dim = int(size * logo_size), then the logo is resized to a square logo_dim × logo_dim — aspect ratio is not preserved; non-square logos are stretched. - A background-coloured pad of logo_dim + 10 px (5 px on each side) is pasted first, then the logo on top with its alpha channel. - logo_size is clamped to 0.05–0.40 by the query schema. 7. Flatten. .convert("RGB") — output PNG has no alpha channel.

Warning

Step 6 is why logo_size above ~0.30 is risky even at EC H: EC H tolerates up to 30% of codewords being unreadable, and a 0.40-size logo plus its pad covers well over that in the centre. Keep logo_size ≤ 0.25 and test-print at your real output size.

Logo fetching

logo_url is fetched server-side with a 15 s timeout, up to 5 redirects, and the platform SSRF guard (private/internal hosts refused). The response is capped at 5 MB after download; larger logos raise ValueError → 400. Only formats Pillow can open are usable (PNG, JPEG, GIF, WebP, BMP, TIFF).

Because the fetch happens after validation but before rendering, a slow logo host directly adds to your request latency. For repeated generation, prefer POST with a pre-encoded base64 logo — it skips the network hop entirely.

import base64, pathlib
logo_b64 = base64.b64encode(pathlib.Path("brand-mark.png").read_bytes()).decode()
# send as body["logo"] in POST /v1/qr/generate — no fetch, no SSRF check, no timeout risk

Examples

Branded PNG with logo (GET)

curl -L -s "https://barcode.toolkitapi.io/v1/qr/generate" \
  -H "X-API-Key: $BARCODE_API_KEY" \
  --get \
  --data-urlencode "data=https://example.com/menu" \
  --data-urlencode "size=800" \
  --data-urlencode "error_correction=H" \
  --data-urlencode "module_shape=rounded" \
  --data-urlencode "fg_color=%231a1a2e" \
  --data-urlencode "bg_color=%23ffffff" \
  --data-urlencode "logo_url=https://example.com/logo.png" \
  --data-urlencode "logo_size=0.22" \
  -o menu-qr.png

file menu-qr.png     # PNG image data, 800 x 800, 8-bit/color RGB, non-interlaced
import httpx

r = httpx.get(
    "https://barcode.toolkitapi.io/v1/qr/generate",
    headers={"X-API-Key": BARCODE_API_KEY},
    params={
        "data": "https://example.com/menu",
        "size": 800,
        "error_correction": "H",       # explicit; becomes H anyway once a logo is used
        "module_shape": "rounded",
        "fg_color": "#1a1a2e",
        "bg_color": "#ffffff",
        "logo_url": "https://example.com/logo.png",
        "logo_size": 0.22,
    },
    follow_redirects=True,
    timeout=30,
)
r.raise_for_status()                   # 400 => bad hex / logo too large / SSRF refused
open("menu-qr.png", "wb").write(r.content)
print(r.headers["content-type"])       # image/png
const qs = new URLSearchParams({
  data: "https://example.com/menu",
  size: "800",
  error_correction: "H",
  module_shape: "rounded",
  fg_color: "#1a1a2e",
  bg_color: "#ffffff",
  logo_url: "https://example.com/logo.png",
  logo_size: "0.22",
});

const res = await fetch(`https://barcode.toolkitapi.io/v1/qr/generate?${qs}`, {
  headers: { "X-API-Key": process.env.BARCODE_API_KEY },
});
if (!res.ok) {
  console.error(res.status, (await res.json()).detail);
  process.exit(1);
}
const { writeFile } = await import("node:fs/promises");
await writeFile("menu-qr.png", Buffer.from(await res.arrayBuffer()));

SVG for print (no logo, no shape)

curl -L "https://barcode.toolkitapi.io/v1/qr/generate?data=https%3A%2F%2Fexample.com&format=svg&fg_color=%231a1a2e&bg_color=%23ffffff&error_correction=Q" \
  -H "X-API-Key: $BARCODE_API_KEY" \
  -o menu-qr.svg
# <svg ... width="330" height="330" class="segno"> — vector, infinite scale
r = httpx.get(
    "https://barcode.toolkitapi.io/v1/qr/generate",
    headers={"X-API-Key": BARCODE_API_KEY},
    params={"data": "https://example.com", "format": "svg",
            "fg_color": "#1a1a2e", "bg_color": "#ffffff", "error_correction": "Q"},
    timeout=30,
)
svg = r.text
assert svg.lstrip().startswith("<?xml") or svg.lstrip().startswith("<svg")
open("menu-qr.svg", "w").write(svg)

Note

SVG colour values are re-emitted as hex from the parsed RGB tuple, so #a00 comes back as #aa0000. Nothing else about the SVG is configurable — if a designer needs shape-rendering="crispEdges", viewBox, or a specific width, patch it in the SVG or generate with your own renderer.

Bulk with per-item styling

POST /v1/qr/bulk accepts up to 20 items, each with its own size, error_correction, colours and module_shape — but no logo fields and PNG only.

curl -s -X POST "https://barcode.toolkitapi.io/v1/qr/bulk" \
  -H "X-API-Key: $BARCODE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "items": [
      {"data": "https://example.com/a", "size": 600, "error_correction": "Q", "module_shape": "rounded", "fg_color": "#1a1a2e"},
      {"data": "https://example.com/b", "size": 600, "error_correction": "M", "module_shape": "square", "fg_color": "#00796b"}
    ]
  }' | jq -r '.results[] | "\(.data) size=\(.size) ec=\(.error_correction) shape=\(.module_shape)"'
import base64, httpx

payload = {"items": [
    {"data": f"https://example.com/p/{i}", "size": 600, "error_correction": "Q",
     "module_shape": "rounded", "fg_color": "#1a1a2e"}
    for i in range(1, 6)
]}
r = httpx.post("https://barcode.toolkitapi.io/v1/qr/bulk",
               headers={"X-API-Key": BARCODE_API_KEY}, json=payload, timeout=60)
r.raise_for_status()
for item in r.json()["results"]:
    name = item["data"].rsplit("/", 1)[-1]
    open(f"{name}.png", "wb").write(base64.b64decode(item["image"]))
const res = await fetch("https://barcode.toolkitapi.io/v1/qr/bulk", {
  method: "POST",
  headers: { "X-API-Key": process.env.BARCODE_API_KEY, "Content-Type": "application/json" },
  body: JSON.stringify({
    items: [
      { data: "https://example.com/a", size: 600, error_correction: "Q", module_shape: "rounded" },
      { data: "https://example.com/b", size: 600, error_correction: "M", module_shape: "square" },
    ],
  }),
});
const { total, results } = await res.json();
console.log(total, results.map((r) => r.size)); // images are base64 PNG, no data: prefix

Bulk is all-or-nothing: the handler raises on the first failing item, so one over-long data string fails the whole batch with 400 Failed to generate QR for '<first 50 chars>': .... Validate lengths client-side before sending.

Scan-testing your output

Always verify a styled code with a real decoder before shipping — styling choices that look fine on screen fail in print.

# 1. Generate
curl -sL "https://barcode.toolkitapi.io/v1/qr/generate?data=https%3A%2F%2Fexample.com&size=600&module_shape=dots_wrong&fg_color=%231a1a2e" \
  -H "X-API-Key: $BARCODE_API_KEY" -o test.png
# → 422, because module_shape is a closed enum (square|rounded|circle|gapped)

# 2. Upload test.png somewhere public, then decode via the API
curl -s "https://barcode.toolkitapi.io/v1/qr/decode?url=https%3A%2F%2Fcdn.example.com%2Ftest.png" \
  -H "X-API-Key: $BARCODE_API_KEY" | jq '.found, .results[].data'
r = httpx.get("https://barcode.toolkitapi.io/v1/qr/decode",
              headers={"X-API-Key": BARCODE_API_KEY},
              params={"url": "https://cdn.example.com/test.png"}, timeout=30)
data = r.json()
assert data["found"] == 1 and data["results"][0]["data"] == "https://example.com", data

To test contrast before you even call the API, compute relative luminance of your fg/bg pair — anything below ~3:1 will struggle at small module sizes:

def _lin(c: int) -> float:
    c /= 255
    return c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4

def contrast(hex_a: str, hex_b: str) -> float:
    def lum(h: str):
        h = h.lstrip("#")
        if len(h) == 3:
            h = "".join(ch * 2 for ch in h)
        r, g, b = (int(h[i:i + 2], 16) for i in (0, 2, 4))
        return 0.2126 * _lin(r) + 0.7152 * _lin(g) + 0.0722 * _lin(b)
    a, b = sorted((lum(hex_a), lum(hex_b)), reverse=True)
    return (a + 0.05) / (b + 0.05)

assert contrast("#1a1a2e", "#ffffff") > 15   # excellent
assert contrast("#00ff00", "#ffffff") < 2   # invisible — do not ship

Errors

Status Cause
400 Invalid hex colour: ...; logo over 5 MB; logo URL that fails after download (a provider HTTPStatusError/timeout is not caught as ValueError and surfaces as 500)
401 Missing/invalid X-API-Key
422 data empty or > 4296 chars; size outside 100–2000; error_correction/format/module_shape outside the enum; logo_size outside 0.05–0.40; logo + logo_url both set
500 QR generation failed: … — renderer exception (e.g. logo bytes that Pillow cannot identify)