How do I convert centimeter to pixel in c# ?
-
1It's important to understand the difference between pixel size (e.g. 1024x768) and resolution (e.g. 72 Dots Per Inch). In common usage, resolution usually really refers to pixel size. – Dercsár Jan 22 '11 at 11:52
-
tnx i did add winforms to my tags – Shahin Jan 22 '11 at 11:53
6 Answers
int CentimeterToPixel(double Centimeter)
{
double pixel = -1;
using (Graphics g = this.CreateGraphics())
{
pixel = Centimeter * g.DpiY / 2.54d;
}
return (int)pixel;
}

- 1,791
- 1
- 14
- 24
You can use the DpiX and DpiY properties of the Graphics object on which you're drawing (which you must have, since conversion is meaningless in the absence of a graphics context of some kind.)
In DpiX and DpiY, the "D" stands for "dots" or pixels, while the "i" stands for "inches". So, it will convert pixels to inches. Then all you have to do is convert inches to centimeters => (x * 2.54)
Also if you want to be more "precise", have a look at the following: HOWTO: How to Make an Application Display Real Units of Measurement
Pixel and centimeter are two different Units they are calculated according to the User's DPI setting. To convert correctly you need to know the DPI of the User Screen.
If you have a 12.8 centimeter display showing a 1280x1024 image, then you have 100 pixels per centimeter.
However you can try using the Graphics.TransformPoints to convert from pixel to cm or opposite.

- 18,056
- 9
- 55
- 79
-
As a note a 12.8cm display is measureing that distance diagonally so it won't be as easy as 100 pixels per centimeter, it will be more than that since the horizontal dsitance is shorter. – Chris Jan 24 '11 at 18:01
-
It was just an example and hat 12.8 cm was for horizontal not diognal...Where do you find a 12.8cm screen with 1280x1024 res (except some tablet i heard which has 300 DPI).. :) – Shekhar_Pro Jan 25 '11 at 02:45
As I said in my comment, you'll have to give more information. (Is this a Windows Forms app? ASP.Net?)
The fundamental approach is:
- Find out the DPI of the output device in question. (It's frequently 96 [96 dots per inch], but you cannot assume that.) This thread may help you do that, if it's a Windows Forms app. Also, the
Graphics
class has theDpiX
andDpiY
members, so you can use those. - Convert the DPI to DPC [dots-per-centimeter] (DPC = DPI / 2.54).
- Multiply your number of centimeters by your DPC value.

- 1,031,962
- 187
- 1,923
- 1,875
-
1@shaahin: Users don't have DPI, devices do. I added a link to a thread about getting DPI, you may have not seen it before posting your comment. – T.J. Crowder Jan 22 '11 at 11:53
-
1@shaahin: Looks like you can get it from `Graphics`, I've updated with a link. – T.J. Crowder Jan 22 '11 at 11:59