Matthew Hipkin

QR Code Generator in Delphi and Lazarus

Download: http://www.matthewhipkin.co.uk/programs/qrgen.zip

Now I must confess this is using the Google Charts API, but it does demonstrate a quick and easy way to get QR barcodes in a Delphi or Lazarus/FreePascal application.

The API requires 3 simple fields be posted to it:

cht=qr this tells Google to create a QR code;
chld=M the error correction level of the QR code (see here for more info);
chs=wxh the width and height of the image to return (eg chs=250x250);
chl=text the URL encoded text to be inserted into the barcode.

The main procedure for the demo application looks like this:

procedure TfrmMain.btnGenerateClick(Sender: TObject);
var
  HTTP: THTTPSend;
  url: String;
  URLData: String;
  png: TPNGObject;
begin
  // URL to post to
  url := 'http://chart.apis.google.com/chart';
  // Generate POST data
  URLData := 'chs='+IntToStr(editWidth.Value)+'x'+IntToStr(editHeight.Value)+'&';
  URLData := URLData + 'cht=qr&chld=M&';
  URLData := URLData + 'chl=' + textText.Text;
  // Create HTTP Object, connect and post
  HTTP := THTTPSend.Create;
  png := TPNGObject.Create;  
  try
    HTTP.Document.Write(Pointer(URLData)^, Length(URLData));
    HTTP.MimeType := 'application/x-www-form-urlencoded';
    HTTP.HTTPMethod('POST', URL);
  except
    showmessage('Unable to connect to Google API!');
    exit;
  end;
  // Load image data
  try
    png.LoadFromStream(Http.Document);
    imgQR.Picture.Assign(png);
  except
    showmessage('Unable to load retrieved image data');
    exit;
  end;
  // Pop up save dialog
  if SavePictureDialog1.Execute then
    png.SaveToFile(SavePictureDialog1.FileName);
  // Clean up
  HTTP.Free;
  png.Free;
end;

There are slight variations in the Delphi and Lazarus/FreePascal versions due to Delphi's handling of PNG images, the Delphi demo was created using Delphi 7 which requires an additional package and some extra lines to handle PNG images.

I am half-way through porting this as a CGI application, which should be available soon.

blog comments powered by Disqus
Flag Counter