Question

convert pixels to centimeters

Asked by: urif

is there any way to convert the amout of pixels traveled by a mouse into centimeters? (or millimeter, or meters, or whatever)
i already have a mouse hook, so that;s no problem, i know where is the mouse is all the time.
code will be greatly appreciated.

thanks

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2005-10-09 at 02:04:57ID21588717
Tags

convert

,

pixels

,

centimeters

Topic

Delphi Programming

Participating Experts
3
Points
100
Comments
19

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Pixels to Inches
    Can you tell me the conversion of pixels to inches?
  2. Converting pixels to millimeters...
    How convert pixels to millimeters?
  3. Converting StdPicture.Width to pixels?
    Hello, How can I convert StdPicture.Width to pixels? For example: Private Sub Form_Click() Dim pic As StdPicture Set pic = LoadPicture("test.jpg") MsgBox CStr(Screen.TwipsPerPixelX) + " x " + CStr(Screen.TwipsPerPixelX) '15 x 15 ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: AmigoJackPosted on 2005-10-09 at 02:55:53ID: 15047353

"pixel" is another dimension length than "meter". always remember that your monitor can display 1024x768 or 800x600 or 640x480 or whatever pixels while it always fills the screen. a mousemove of virtually 2cm on a 800x600 display would be virtually 4cm on a 400x300 display (as example). see what i mean?

 

by: urifPosted on 2005-10-09 at 04:30:01ID: 15047480

yes i know, still do you know how to do it?

take a look at this code, it's not useful but it'll give you a good idea of what can be done

http://www.delphipages.com/threads/thread.cfm?ID=115788&G=115786

or

http://delphi.about.com/od/adptips2005/qt/pixel2mm.htm (but the code is a mess and i can't seem to be able to fix it)

 

by: mikelittlewoodPosted on 2005-10-09 at 04:36:13ID: 15047491

Amigo is right.

You would be able to calculate the position of a mouse using the CursorPos position I think to get the start and end points. This would give you the number of pixels travelling in the X and  axis, but you dont have a reference point due to screen resolution.

You would need to work from a standard resolution, and calculate a base pixel distance to cover a centimetre. You could then extrapolate for other resolutions from this base figure.

So say you worked on a 800x600 screen and you found that 1cm = 20 pixels on the X axis and 1cm = 15 pixels on the Y axis.

Therefore a 1200x1024 screen, X axis (1200/800)x20 = 30 pixels, Y axis (1024/600)x15 pixels.

I think my maths is correct.

 

by: mikelittlewoodPosted on 2005-10-09 at 04:40:52ID: 15047503

I like that second example you showed. This is pretty much using the same maths calculation as I described above.

Rsolution / Size

Can you not get it to work?

 

by: AmigoJackPosted on 2005-10-09 at 05:45:21ID: 15047608

seems like the example has a few typos. try this (havent tested tho)


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;
~~~~~~~~~~~~~~~~~~~~~~~~~

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

   mmx := Trunc(468 / cx) ;
   mmy := Trunc(60 / cy) ;
end;

 

by: urifPosted on 2005-10-09 at 06:29:23ID: 15047712

i have the same problem here, handle of what!?

> PixelsPerMM(Handle,cx,cy) ;

the error is Incompatible types: TCanvas  and HWND

 

by: AmigoJackPosted on 2005-10-09 at 06:53:27ID: 15047762

well, try form1.canvas or canvas or the canvas of sth else ;-)

 

by: urifPosted on 2005-10-09 at 07:31:36ID: 15047825

i'd a[[reciate it if you can show me how this work?
it doesn't seem to work, not for form1.canvas, not passing the desktop as canvas, etc. i ask my question again:

is there any way to convert pixels to cm or mm or m, or whatever and know how much the mouse traveled?

 

by: urifPosted on 2005-10-09 at 07:41:41ID: 15047842

by the way if you want to know why i need this code visit my page at
www.geocities.com/uf_new
i'm writing a mouse application with ergonomics in mind, since i developed an RSI case. part of it is how much mouse movement a user produces on each session

 

by: rllibbyPosted on 2005-10-09 at 10:44:18ID: 15048310

This should do it for you.

Regards,
Russell

function PixelHorizToMM(PixelX: Integer): Integer;
var  hdcDesk:       HDC;
begin
  hdcDesk:=GetDC(0);
  try
     result:=Trunc(PixelX * (GetDeviceCaps(hdcDesk, HORZSIZE) / GetDeviceCaps(hdcDesk, HORZRES)));
  finally
     ReleaseDC(0, hdcDesk);
  end;
end;

function PixelVertToMM(PixelY: Integer): Integer;
var  hdcDesk:       HDC;
begin
  hdcDesk:=GetDC(0);
  try
     result:=Trunc(PixelY * (GetDeviceCaps(hdcDesk, VERTSIZE) / GetDeviceCaps(hdcDesk, VERTRES)));
  finally
     ReleaseDC(0, hdcDesk);
  end;
end;

function PixelPointToMM(PixelPt: TPoint): TPoint;
begin
  result:=Point(PixelHorizToMM(PixelPt.x), PixelVertToMM(PixelPt.y));
end;

 

by: rllibbyPosted on 2005-10-09 at 11:08:26ID: 15048375

Please note, converting to CM (or even to MM) should probably be done as double result, due to the resolution difference.

Eg;

1024 px screen width = 320 mm screen width, so it takes 3.2 pxls = 1 mm, or 1pxl = 0.3125 mm

Russell


 

by: urifPosted on 2005-10-09 at 12:44:33ID: 15048629

ok, let me try it,
a question tho, why do you want to return a tpoint in function PixelPointToMM?

 

by: rllibbyPosted on 2005-10-09 at 15:48:00ID: 15049175


I was only trying to be complete; X coord px conversion, Y coord px conversion, and TPoint (which would be useful if you were doing an (X px, Y px) -> (X mm, Y mm) conversion. If you don't need it, then don't use it.

Russell




 

by: urifPosted on 2005-10-09 at 20:46:03ID: 15049958

excuse my ignorance, i just don't see where the mm are in a tpoint...
i understand that the 1st 2 functions return integer and that they return mm, the last function returns a tpoint so i am having trouble understanding the whole idea behind it.

 

by: rllibbyPosted on 2005-10-09 at 21:03:25ID: 15050004


When dealing with the mouse, one of the most common structures is the TPoint, which is a structure to hold both the horiz/vert position. The X, Y values are integer data types, and the resolution is assumed to be in pixels.
All I did was provide you a helper function that takes both a horiz and vert pixel measurement and converts it to millimeter in one call. Eg:

var  ptCursorInMM:  TPoint;
begin

  // Convert mouse position in pixels to point structure in mm
  ptCursorInMM:=PixelPointToMM(Mouse.CursorPos);

  // ptCursorInMM.X is the horiz measurement now in MM
  // ptCursorInMM.Y is the vert measurement now in MM

end;

Or, for example, you are trying to convert the width/height of something in pixels -> mm.  Its nothing more than a conversion helper function, thats all. So I will say again, if you don't need it, then don't use it.

Russell


 

by: urifPosted on 2005-10-10 at 00:45:09ID: 15050613

ok, every time the mouse move i call this function (quick and dirty):
posx and posy are integers that are updated every time the mouse move (by the mouse hook) so they are always updated with the latest position of the mouse.

procedure TForm1.Mousetravel;
var
 traveled, currpos:tpoint;
 total:integer;
begin
    currpos.X:=posx;
    currpos.Y:=posy;
    traveled:=PixelPointToMM(currpos);
    total:=traveled.X+traveled.Y;
form2.StaticText2.Caption:=inttostr(strtoint(form2.StaticText2.Caption)+total);
end;

even tho i move the mouse the values are being updated randomly and without any logic (seemingly).
i will give you the points, since the answer seems to work, but again what i need in the total (in mm, cm or whatever in metric) that the mouse traveled until it stops. so, any ideas?

thanks

 

by: urifPosted on 2005-10-10 at 01:23:53ID: 15050701

this is how the function looks at the moment (to km)

procedure TForm1.Mousetravel;
var
 traveled, currpos:tpoint;
 total:integer;
 km:double;
begin
    currpos.X:=posx;
    currpos.Y:=posy;
    traveled:=PixelPointToMM(currpos);
    total:=traveled.X+traveled.Y;
    km:=(total*0.001)*0.001;
    form2.StaticText2.Caption:=FloatToStrF(StrToFloat
                               (form2.StaticText2.Caption)+
                               km, ffNumber, 8, 4);
end;

 

by: rllibbyPosted on 2005-10-10 at 08:28:27ID: 15052912

urif,

Two things stand out. First, I already mention this; you will find the resolution between pixels/mm to be such that a double value should be used. Eg, on my system

3.2 pxls = 1 mm, or 1pxl = 0.3125 mm

So moving one pixel would yield 0 mm in integer format. (It takes 3.2 pixels to yield 1 mm).

Second, your math for determining distance is incorrect. Take for example the following. You start at a position of (0,0) and then move to (1,1). Using your math, you will have calculated a move of 2 units.

total:=traveled.X+traveled.Y

This is incorrect, as the distance traveled is actually 1 unit.

You didn't mention this before, only that you required a conversion from pixels to mm. The conversion routines ARE correct, but again, should probably be scaled to double for greater accuracy. If you would like, I will provide these as well as the correct algo for distancing.

Regards.
Russell
 




 

by: rllibbyPosted on 2005-10-10 at 09:31:34ID: 15053374


The following is code for:

-  pixel->mm conversion routines that yeild a double result
-  handling for a point structure of double (X,Y)
-  distance caclulation using the double point structure, where X = horiz distance traveled, and Y = vert distance traveled.

The one thing that bothers me is that you indicate posx/posy represent the current mouse position as updated by your mouse hook. If this is the case, then what are you measuring distance from? I.e., where is the starting point? You don't appear to store the last position checked, so as it stands, your calculations would be from the screen position of (0,0). Am I missing something?


Regards,
Russell

--------


unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;

type
  TDoublePoint      =  packed record
     x:             Double;
     y:             Double;
  end;

function   DoublePoint(X, Y: Double): TDoublePoint;
function   PixelHorizToMM(PixelX: Integer): Double;
function   PixelVertToMM(PixelY: Integer): Double;
function   PixelPointToMM(PixelPt: TPoint): TDoublePoint;
function   Distance(Traveled: TDoublePoint): Double;

type
  TForm1            =  class(TForm)
     procedure      FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
     procedure      FormCreate(Sender: TObject);
  private
     // Private declarations
     FLastPoint:    TDoublePoint;
  public
     // Public declarations
  end;

var
  Form1:            TForm1;

implementation
{$R *.DFM}

function DoublePoint(X, Y: Double): TDoublePoint;
begin
  result.x:=X;
  result.y:=Y;
end;

function PixelHorizToMM(PixelX: Integer): Double;
var  hdcDesk:       HDC;
begin
  hdcDesk:=GetDC(0);
  try
     result:=PixelX * (GetDeviceCaps(hdcDesk, HORZSIZE) / GetDeviceCaps(hdcDesk, HORZRES));
  finally
     ReleaseDC(0, hdcDesk);
  end;
end;

function PixelVertToMM(PixelY: Integer): Double;
var  hdcDesk:       HDC;
begin
  hdcDesk:=GetDC(0);
  try
     result:=PixelY * (GetDeviceCaps(hdcDesk, VERTSIZE) / GetDeviceCaps(hdcDesk, VERTRES));
  finally
     ReleaseDC(0, hdcDesk);
  end;
end;

function PixelPointToMM(PixelPt: TPoint): TDoublePoint;
begin
  result:=DoublePoint(PixelHorizToMM(PixelPt.x), PixelVertToMM(PixelPt.y));
end;

function Distance(Traveled: TDoublePoint): Double;
begin

  // The Traveled values represent the amount of distance traveled, where X is the
  // horizontal distance, and Y is the vertical distance. These values can be signed
  // as either positive or negative. This allows calculating from a virtual starting
  // point of (0,0).
  result:=Abs(Sqrt(Sqr(0-Traveled.x) + Sqr(0-Traveled.y)));

end;

procedure TForm1.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
var  dpCurrent:     TDoublePoint;
     dpTraveled:    TDoublePoint;
begin

  // Get current position
  dpCurrent:=PixelPointToMM(Point(X, Y));

  // Calculate the distance traveled in (X, Y) values
  dpTraveled:=DoublePoint(dpCurrent.x-FLastPoint.x, dpCurrent.y-FLastPoint.y);

  // Display distance in mm
  Caption:=FloatToStr(Distance(dpTraveled));

  // Update the last point
  FLastPoint:=dpCurrent;

end;

procedure TForm1.FormCreate(Sender: TObject);
begin

  // Set the last starting point
  FLastPoint:=DoublePoint(0, 0);

end;

////////////////////////////////////////////////////////////////////////////////
//   Applying the procedures to your code
////////////////////////////////////////////////////////////////////////////////
//
//
//   procedure TForm1.Mousetravel;
//   var
//      traveled:   TDoublePoint;
//      total:      Double;
//      km:         Double;
//   begin
//      traveled:=PixelPointToMM(Point(posx, posy));
//      total:=Distance(traveled);
//      km:=(total * 0.001) * 0.001;
//
//      ... remaining code to display or do whatever
//
//   end;
//
////////////////////////////////////////////////////////////////////////////////

end.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...