Contents · Forum Home · StreamSec Tools 4.1.5.365 documentation

Encode text as a QR code and read it back from an image

Use the VCL QR image adapter to write a Delphi string as a PNG, then read the text from the pixels of that PNG.

Write a QR code to a PNG stream

uses
  System.Classes, Vcl.Graphics, Vcl.Imaging.pngimage,
  StreamSec.QR.Encode, StreamSec.QR.Decode, StreamSec.QR.Image.VCL;
procedure WriteQrPng(const aText: string; aOutput: TStream);
const
  cPixelsPerModule = 6;
  cQuietModules = 4;
var
  lBitmap: TBitmap;
  lPng: TPngImage;
begin
  lBitmap := TBitmap.Create;
  try
    QrDrawText(aText, lBitmap, qrEcM, cPixelsPerModule, cQuietModules);
    lPng := TPngImage.Create;
    try
      lPng.Assign(lBitmap);
      lPng.SaveToStream(aOutput);
    finally
      lPng.Free;
    end;
  finally
    lBitmap.Free;
  end;
end;

Pass your text and a writable stream to WriteQrPng. For a PNG file, open a new TFileStream with fmCreate. The caller owns the stream.

QrDrawText converts the string to UTF-8 bytes and selects a QR version that fits them at error correction level M. A module is one square in the symbol. The sample draws each module six pixels wide and leaves a white margin four modules wide on every side. Keep this quiet zone when you display or print the image. If the UTF-8 payload is too large for the encoder at the selected level, it raises eQrEncode.

Read the text from the PNG

function ReadQrPngText(aInput: TStream): string;
var
  lPng: TPngImage;
  lDecoded: tQrDecoded;
begin
  lPng := TPngImage.Create;
  try
    lPng.LoadFromStream(aInput);
    lDecoded := QrReadGraphic(lPng);
    Result := lDecoded.AsText;
  finally
    lPng.Free;
  end;
end;

Open the PNG for reading, or set Position := 0 if you wrote it to a new memory stream. Pass the stream to ReadQrPngText. QrReadGraphic locates the symbol in the loaded image and decodes its bytes. AsText interprets those bytes as UTF-8. For a symbol carrying binary data, use the decoded record's Data field.

A blank image raises eQrNotFound. A located symbol whose data cannot be corrected can raise eQrUnreadable. See the QR code notes for the supported symbol versions and image formats.

Reference

StreamSec.QR.Encode · StreamSec.QR.Decode · StreamSec.QR.Image · StreamSec.QR.Image.VCL