1. About.com
  2. Computing & Technology
  3. Delphi

Discuss in my forum

How to Convert Pixels to Millimeters

By , About.com Guide

If you need to convert pixel value to millimeters (inches, centimeters, etc.) use the code provided here.

The code uses the API function GetDeviceCaps to get the metrics you need.

~~~~~~~~~~~~~~~~~~~~~~~~~
procedure PixelsPerMM(
   canvas: TCanvas;
   var x, y: single) ;
var
    H:HDC;
    hres,vres,
    hsiz,vsiz:integer;
begin
    H:=canvas.handle;
    hres := GetDeviceCaps(H,HORZRES) ; {display width in pixels}
    vres := GetDeviceCaps(H,VERTRES) ; {display height in pixels}
    hsiz := GetDeviceCaps(H,HORZSIZE) ; {display width in mm}
    vsiz := GetDeviceCaps(H,VERTSIZE) ; {display height in mm}
    x := hres/hsiz;
    y := vres/vsiz;
end;
~~~~~~~~~~~~~~~~~~~~~~~~~

Now, to actually convert an amount of pixels, let's say 468, to milimeters, use the next steps:

1. First, call the conversion function only once to get the pixel per milimeter ration for the required device (Screen, Printer, ...)

2. Next, transform an amount of pixels to millimeteres, depending on the orientation (horizontal, vertical)

~~~~~~~~~~~~~~~~~~~~~~~~~
var
   cx, cy : single;
   mmx, mmy : integer;
begin
   PixelsPerInch(Handle,cx,cy) ;

   mmx := Trunc(468 / PixelsInMM.y) ;
   mmy := Trunc(60 / PixelsInMM.y) ;
end;
~~~~~~~~~~~~~~~~~~~~~~~~~

Delphi tips navigator:
» TForm.Create(?) Nil, Self or Application?
« How to create a Console mode application Without a console window using Delphi

©2012 About.com. All rights reserved. 

A part of The New York Times Company.