Search code examples
c#winformssystem.drawing

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?


Solution

  • 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);