How a QR Code Is Found and Decoded in an Image
A step-by-step look at how a decoder finds and reads a QR code: binarization, finder and alignment patterns, format information, masking, Reed-Solomon error correction, and why scans fail.
A QR code looks like noise, but it is a remarkably disciplined structure. Every QR symbol carries a small set of fixed landmarks whose only job is to let a decoder find the code, work out how it is rotated and scaled, and rebuild the grid of black and white squares (called modules) before a single bit of your data is read. Most of the bytes in a QR code are not your URL or Wi-Fi password at all. A large share is redundancy that lets a scanner reconstruct the message even when part of the symbol is dirty, washed out by glare, or hidden under a logo.
This post follows the path a decoder takes from a raw camera frame to a decoded string. The examples use jsQR, a popular open-source JavaScript decoder that runs entirely in the browser, but the stages are the same in any QR reader, because they come from the QR specification itself (ISO/IEC 18004).
In outline: locate three corner squares, lock onto the grid they imply, read a handful of metadata modules, undo a masking pattern, then run error correction over the result. Each step depends on the one before it, which is why a blurry or skewed image fails early rather than producing garbage.
What the decoder is handed
Before any QR logic runs, a picture has to become a flat array of pixels. In a browser, the usual route for both camera frames and uploaded images is the same: draw the source onto a <canvas>, then call getImageData. A minimal decode with jsQR looks like this:
import jsQR from 'jsqr';
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d', { willReadFrequently: true });
canvas.width = source.videoWidth || source.naturalWidth;
canvas.height = source.videoHeight || source.naturalHeight;
ctx.drawImage(source, 0, 0, canvas.width, canvas.height);
const { data, width, height } = ctx.getImageData(0, 0, canvas.width, canvas.height);
const code = jsQR(data, width, height, { inversionAttempts: 'attemptBoth' });
if (code) {
console.log(code.data); // the decoded text
console.log(code.version); // 1 to 40
}
data is a Uint8ClampedArray of RGBA bytes, four per pixel, in row-major order. That is the only input the decoder needs: the raw pixel buffer plus its width and height. Everything else is computed.
The willReadFrequently option is a hint to the browser that the canvas will be read back repeatedly, so it should keep the pixels somewhere cheap to copy from rather than on the GPU. That matters most for a live camera, where a scanner typically reads one frame per animation frame with requestAnimationFrame and stops the loop the moment a code is found.
The inversionAttempts option controls whether jsQR also tries the image with light and dark swapped, which is how it finds white-on-black codes. Trying both (the default) costs a second pass on every image where the normal reading fails. On a live feed, where most frames contain no code at all, some scanners skip inversion to save that work, at the price of never reading an inverted code. For a single uploaded image, which gets only one chance, trying both is the obvious choice.
jsQR returns at most one code per call. A picture that holds several codes side by side can confuse it, since it may pair finder patterns from different symbols, so reading every code in such an image means scanning it in smaller sections.
Binarization: from grayscale to black and white
The decoder does not work on color. Its first internal step is to convert the RGBA buffer to grayscale and then to a pure binary image, where every pixel is classed as dark or light. This matters more than it sounds. A photo of a QR code has gradients, shadows and uneven lighting, so a single global threshold ("anything darker than 128 is black") fails the moment one corner is in shadow.
jsQR uses a local, adaptive threshold instead. It divides the image into a grid of small blocks and computes a separate threshold for each one from the brightness of the blocks around it. A pixel in the shadowed corner is compared against its dark neighbors, not against the bright opposite corner. The output of this stage is a clean bitmap of true and false values that the geometry stage can reason about.
Finder patterns: the three corner squares
The three nested squares in the corners are the finder patterns, and they are the heart of detection. Each one is a 7x7 module block: a solid 3x3 center, a one-module light ring, and a one-module dark ring around that. The decisive property is the ratio of dark and light runs along any line passing through the center: 1:1:3:1:1.
A decoder scans the binarized image row by row, measuring runs of consecutive same-colored pixels. When it finds a run sequence whose lengths match that 1:1:3:1:1 proportion (within tolerance), it has a candidate finder pattern crossing that row. It then checks that the same ratio holds vertically and diagonally through the candidate center. The ratio is scale-invariant: it holds whether the code fills the frame or is a thumbnail, because it describes proportions rather than absolute pixel counts.
| Element | Size (modules) | Role |
|---|---|---|
| Finder pattern | 7x7, three of them | Locate, orient, and scale the symbol |
| Separator | 1-module white border | Isolate each finder from data |
| Alignment pattern | 5x5, count depends on version | Correct perspective distortion |
| Timing patterns | alternating row and column | Establish the exact module pitch |
Three finder patterns, rather than four, is a deliberate choice. Three points are enough to fix an orientation: the decoder works out which corner has no finder and therefore which way is "up." The arrangement of the three centers gives the rotation, so a code photographed upside down or sideways still decodes, however you hold your phone.
Alignment patterns and the module grid
Finder patterns give you three corners. For small codes that is almost enough, but bigger symbols are physically larger, and a phone held at an angle introduces perspective distortion: the far edge of the code is rendered smaller than the near edge, so the grid is not a perfect square in the image. Straight grid math would drift and start sampling the wrong module halfway across.
Alignment patterns fix this. They are smaller 5x5 squares (with the same nested look) placed at known interior coordinates. Version 1 codes (the smallest, 21x21 modules) have none, and larger versions add more of them in a regular layout. The decoder locates these interior anchors and uses them, together with the finder centers, to compute a perspective transform that maps image coordinates to grid coordinates. Once that transform exists, the decoder can ask "what is the color at module (row, col)?" and sample the correct pixel even on a warped photo.
The timing patterns, the alternating dark and light lines running between the finders, let the decoder count modules precisely and confirm the grid pitch it inferred. Together these landmarks turn a skewed photograph into a clean matrix of true and false cells.
Format and version information
With the grid sampled, the decoder still does not know how to interpret the cells. Two pieces of metadata come first.
Version tells the decoder the symbol size. Versions run from 1 (21x21 modules) up to 40 (177x177), growing by four modules per side at each step. For versions 7 and above there is a dedicated version information block near the corners; for smaller versions the size is implied by the geometry. Get this wrong and every subsequent coordinate is off.
Format information is the more important of the two. It is a 15-bit field, stored twice (once near the top-left finder, once split across the other two), that encodes the error correction level and the mask pattern. Storing it twice, and protecting it with its own BCH error-correcting code, means the decoder can almost always recover the format even if one copy is damaged. Without it you cannot unmask the data, so the format bits are defended harder than the payload.
The error correction level is one of four:
| Level | Approx. recovery capacity |
|---|---|
| L | up to ~7% of codewords |
| M | up to ~15% |
| Q | up to ~25% |
| H | up to ~30% |
Masking: why QR codes look random
If you encoded a URL straight into the grid, you might get large solid blocks of black or white, or accidental shapes that resemble finder patterns. Both confuse scanners. To avoid this, the encoder XORs the data region with one of eight mask patterns, simple formulas over the module coordinates such as "invert this cell if (row + col) is even." The encoder scores each candidate with a set of penalty rules, keeps the one that produces the most balanced, least confusing layout, and records its index in the format information.
Decoding reverses this. The decoder reads the mask index from the format bits, regenerates the same pattern, and XORs it back out of the data region (the finder, timing and alignment areas are never masked, so they are skipped). What remains is the real codeword stream. The step is purely deterministic; once the mask index is known, there is no guessing.
encode: data_bits XOR mask(row, col) -> stored module
decode: stored module XOR mask(row, col) -> data_bits
Reed-Solomon: why a logo can sit on top
The unmasked stream is not raw bytes yet. QR codes protect data with Reed-Solomon error correction, the same family of codes used on CDs and in deep-space transmission. The encoder splits the message into data codewords and appends error-correction codewords computed over them. Reed-Solomon works on whole bytes (technically symbols in the finite field GF(256)), which is why it shrugs off a smear that wipes out a contiguous patch. A damaged region corrupts a bounded number of codewords, and as long as that count stays within the code's correction capacity, the original message is recovered exactly.
That is what lets you drop a logo into the middle of a QR code. The logo destroys some modules, but if the symbol was generated at error correction level Q or H, there is enough redundancy that the corrupted codewords stay within the recoverable budget. The logo has no special status; the code simply tolerates a certain number of wrong codewords, and the logo spends part of that allowance. Cover too much, or add dirt and glare on top of a logo, and you exceed the limit and decoding fails. Larger codes also interleave their codewords into several blocks, so damage is spread across blocks rather than overwhelming one, which raises the practical tolerance for a single blemish.
Only after Reed-Solomon succeeds does the decoder read the data codewords: a mode indicator (numeric, alphanumeric, byte, or kanji), a length, and the payload bytes. What comes out is a string, and the meaning of that string is a matter of convention rather than of the QR standard. A web link starts with https://, Wi-Fi credentials start with WIFI:, a contact card starts with BEGIN:VCARD, and mailto:, tel:, sms: and geo: mark email addresses, phone numbers, text messages and map locations. A reader that recognizes these prefixes can show the payload as a contact, a network or a link instead of a raw line of text.
Why scans fail, in pipeline order
Because each stage feeds the next, you can map common failures to the step that breaks:
- Blur or low resolution: binarization cannot resolve individual modules, so the finder ratios never match. A decoder needs a few pixels per module to measure those runs at all. On a live feed, the scanner simply finds nothing and tries the next frame.
- Extreme angle or fold: the finder patterns are found, but the perspective transform is unreliable and sampling lands between modules. Alignment patterns help, but only up to a point.
- Glare or heavy occlusion: the grid samples fine, but too many codewords are wrong and Reed-Solomon runs out of correction capacity.
- Inverted colors: a decoder that only looks for dark modules on a light background misses them entirely, which is why jsQR can retry with light and dark swapped.
The first two failures are the most common in practice, and both are fixed the same way: hold the camera steady, square to the code and close enough to fill a good part of the frame, in even light. Give binarization and finder detection a clean image and the rest of the pipeline almost always follows.
Try it
To watch this pipeline run, open the QR Code Reader & Scanner on Loopaloo. It decodes from an uploaded image or a live camera feed entirely in your browser, with nothing uploaded to a server, and it tries both dark-on-light and light-on-dark readings. When a picture does not decode as it is, the reader retries with a few cleanups (flattening transparency onto white, stretching the contrast, converting to grey, sharpening, resizing) and lists each attempt so a failed scan is not a mystery. It also reports the symbol's version and size in modules. To see the encoding side, including the error correction level that makes all of the above possible, the QR Code Generator builds codes you can read straight back. Generate a code at level H, cover part of it, and scan it again: it is a quick, hands-on way to watch Reed-Solomon recovery at work.
Related Tools
QR Code Reader & Scanner
Read QR codes from a photo, a screenshot or your camera, several at once. Wi-Fi logins, contacts, events and links are laid out field by field, in your browser.
QR Code Generator
Make QR codes for links, Wi-Fi, contacts, events and payments as you type, check that each one scans, and download it as PNG or SVG.