Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Pixels to Inches and vice versa in C#

I am looking to convert pixes to inches and vice versa. I understand that I need DPI, but I am not sure how to get this information (e.g. I don't have the Graphics object, so that's not an option).

Is there a way?

like image 419
AngryHacker Avatar asked Jan 23 '09 22:01

AngryHacker


People also ask

How do I convert pixels to inches?

Take the number of pixels and divide by the display's PPI (pixels per inch) specification. For example, 200 pixels on an 81 PPI screen would convert to 200 / 81 = 2.5 inches .

What is 1920x1080 pixels in CM?

1920 px = 50.8 cm Convert 1920 px with dpi to cm.


1 Answers

On a video device, any answer to this question is typically not very accurate. The easiest example to use to see why this is the case is a projector. The output resolution is, say, 1024x768, but the DPI varies by how far away the screen is from the projector apeture. WPF, for example, always assumes 96 DPI on a video device.

Presuming you still need an answer, regardless of the accuracy, and you don't have a Graphics object, you can create one from the screen with some P/Invoke and get the answer from it.

Single xDpi, yDpi;

IntPtr dc = GetDC(IntPtr.Zero);

using(Graphics g = Graphics.FromHdc(dc))
{
    xDpi = g.DpiX;
    yDpi = g.DpiY;
}

if (ReleaseDC(IntPtr.Zero) != 0)
{
    // GetLastError and handle...
}


[DllImport("user32.dll")]
private static extern IntPtr GetDC(IntPtr hwnd);    
[DllImport("user32.dll")]
private static extern Int32 ReleaseDC(IntPtr hwnd);
like image 68
codekaizen Avatar answered Sep 22 '22 14:09

codekaizen