Skip to content
Tutorials Center
My learning

Topics

Lesson 144 of 156 Β· Projects

Project: QR Generator and Image Resizer

Build a QR code generator with your own encoder and an image resizer and compressor with canvas, toBlob and quality sliders, then download the results.

Two tools that people constantly search for are a QR code generator and an image resizer. Neither needs a server: the browser can draw pixels on a <canvas>, turn them into a file with toBlob() and hand that file to the visitor.

In this project you will build both. The image tool is mostly canvas arithmetic. The QR generator is more adventurous: instead of pasting in a library, you will write a small, real QR encoder yourself (about 200 lines) so you can see how the pattern is made. It is verified to produce codes that standard phone scanners read, for text up to a few hundred bytes. For production work, a maintained library is still the right choice, because it supports every QR version, every data mode and all four error-correction levels.

You will use ideas from Canvas Drawing from JavaScript, Files and Blobs and Typed Arrays.

How a QR code works

A QR code is a square grid of dark and light modules. Its size depends on the version: version 1 is 21 by 21 modules, and every version adds 4 per side (version * 4 + 17). The grid contains:

  • three finder patterns (the big squares in three corners) that tell a scanner where the code is and how it is rotated;
  • timing patterns (alternating dots between finders) and, from version 2, alignment patterns that keep the grid straight;
  • format information (error-correction level and mask number), stored twice with its own error correction;
  • from version 7, version information;
  • everything else: your data followed by error-correction codewords.

Making a code is a pipeline:

  1. Convert the text to UTF-8 bytes and add a header (the mode 0100 for bytes and the length) and padding.
  2. Compute Reed–Solomon error-correction bytes, so that a scanner can rebuild the message even if part of the code is dirty or covered. Longer messages are split into several blocks, each with its own correction bytes, and the bytes are interleaved.
  3. Place the bits in a zigzag over the free modules, two columns at a time, starting at the bottom right.
  4. Apply one of eight mask patterns that flips modules to avoid large blocks of one colour, which scanners find hard to read. The encoder tries all eight and keeps the one with the lowest penalty score.

The error-correction level trades capacity for robustness: L can repair about 7% damage and M about 15%.

Step 1: Reed–Solomon in a few lines

Reed–Solomon works with numbers in a Galois field with 256 elements (every byte is one). Addition is XOR, and multiplication is a shift-and-XOR loop that reduces by the polynomial 0x11D. The error-correction bytes for a block are the remainder of dividing the data, as a polynomial, by a generator polynomial.

You can check the code against a well-known published example: the data codewords of the text "HELLO WORLD" at level M in version 1 are 32 91 11 120 209 114 220 77 67 64 236 17 236 17 236 17, and the ten error-correction bytes are 196 35 39 119 235 215 231 226 93 23.

JS Step 1: Reed-Solomon error correction

Press Run (or Ctrl + Enter) to see the console output here.

No output.

When the printed ECC bytes match the published ones, your Galois-field arithmetic and long division are right. A single wrong bit in either would change every byte of the output, which makes this a very sensitive test.

Step 2: The generator

Here is the whole encoder, then the page around it. Read it top to bottom; the comments mark the pipeline from above. The makeQr(text, level) function returns { version, size, mask, modules }, where modules[y][x] is true for a dark module.

Things worth noticing:

  • Version selection is a loop: try version 1, and move up until the data fits the capacity (capacityBits).
  • fixed[][] marks modules that belong to the function patterns, so data bits and masks only touch the free ones.
  • The zigzag loop skips column 6 (the vertical timing pattern), which is why right jumps from 7 to 5.
  • The penalty function here is a simplified version of the standard's four rules. Every mask produces a valid code; the penalty only decides which one scans best.
Step 2: QR code generator

Try pointing a phone camera at the screen. Then type a very long text and watch the version climb until the encoder refuses it. Switch from L to M and notice that the same text may need a bigger version, because more of the space is spent on error correction.

Always keep the quiet zone (the light border) and a strong contrast between dark and light. Inverted colours (light on dark) are not read by every scanner, so stay with dark modules on a light background.

Step 3: Resizing images with canvas

To resize an image in the browser, draw it onto a smaller canvas with drawImage(image, 0, 0, newWidth, newHeight). The only maths is choosing the new size while keeping the aspect ratio, and (usually) never enlarging a small picture:

JS Step 3: Size maths

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Step 4: A resizer with a live size readout

For smooth results, set ctx.imageSmoothingQuality = "high". Then canvas.toBlob(callback, type, quality) turns the pixels into a file. The quality argument (0 to 1) only affects lossy formats, image/jpeg and image/webp; PNG is lossless and ignores it. That is why photos shrink dramatically as JPEG and screenshots with flat colours may be smaller as PNG.

The demo below creates its own "photo" so it needs no upload. In your own page, replace it with the visitor's file: const bitmap = await createImageBitmap(input.files[0]) gives you an image with width and height to draw.

Step 4: Resize and compress

Drag Quality down and watch the byte count fall; switch to PNG and notice the quality slider has no effect. Note the fallback line: when a browser cannot encode a requested format (older Safari has no WebP encoder), toBlob() quietly returns a PNG, and checking blob.type is how you find out.

Some practical points for a real resizer:

  • Downscale in steps for very large reductions. Shrinking a 6000 px photo to 200 px in one drawImage can look jagged; halving a few times first gives smoother results.
  • Respect orientation. Phone photos carry a rotation flag; createImageBitmap(file) applies it by default in current browsers.
  • Release memory. Call bitmap.close() when you no longer need an image, and URL.revokeObjectURL() for every object URL you created.
  • Cross-origin images taint the canvas. If you draw an image from another site without CORS headers, toBlob() throws a SecurityError. Files the visitor picks are never a problem.

Ideas to extend it

  • Custom QR colours and a logo. Draw a small logo in the centre. This is why error correction exists, but keep it below the level's damage budget (and test with a phone).
  • Other QR content types: Wi-Fi (WIFI:T:WPA;S:name;P:password;;), contacts (BEGIN:VCARD), and mailto: links are just text with a convention.
  • Batch resize many files with Promise.all, then zip them or download one by one.
  • Crop tool using coverCrop() for square avatars.
  • A progress and error UI for files that are not images (file.type.startsWith("image/")).

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. What does the quality argument of canvas.toBlob(callback, type, quality) affect?

    PNG is lossless, so it ignores quality. JPEG and WebP trade file size against visual quality using that number.
  2. 2. Why does a QR code contain error-correction codewords?

    Reed-Solomon codewords add redundancy. Level L can repair about 7% damage, M about 15%. They do not hide or compress the data.
  3. 3. How many modules per side does a version 5 QR code have?

    The size is version * 4 + 17, so version 5 is 37 by 37 modules.
  4. 4. What does fitWithin() do with Math.min(1, ...)?

    The scale is the smallest of 1 and the ratios to the limits, so it never exceeds 1. A small picture keeps its size.
  5. 5. Why might toBlob() throw a SecurityError after you draw an image on the canvas?

    A canvas that has drawn cross-origin pixels without permission is tainted, and reading it back is blocked for privacy.

Summary

  • A QR code is a grid of modules: finder, timing and alignment patterns, format information, then data plus Reed–Solomon error correction, masked to avoid large single-colour areas.
  • Version v is 4v + 17 modules per side; the encoder picks the smallest version that fits and the best of eight masks.
  • Reed–Solomon is polynomial division in GF(256): shift-and-XOR multiplication and a remainder.
  • Draw modules with fillRect() and always keep a 4-module quiet zone with dark-on-light contrast.
  • Resize with drawImage() into a smaller canvas, computing the size from the aspect ratio and never upscaling.
  • toBlob(callback, type, quality) makes the file; quality applies to JPEG and WebP only, and blob.type shows what the browser really produced.
  • Release object URLs and bitmaps, and remember that cross-origin images taint the canvas.

Next: Project: Dark Mode, Mobile Nav, Expanding Cards, Accordion.