In GTK/Linux, what’s the correct way to get the DPI scale factor?

I haven’t seen a dpi getter in GTK, but with some lines of code from open sources and some changes, I usually ask the X-server with this code-snippet to get the dpi values for the x and y direction. For the displayname you can pass the value(s) you want via argv[].

If you name it ‘getdpi.c’ then compile with

gcc -Wall -std=c99  -o getdpi getdpi.c -lX11

If it helps you, a vote would be appreciated. 🙂

#include <X11/Xlib.h>

#include <stdio.h>
#include <stdlib.h>

const static unsigned int FALSE = 0;
const static unsigned int TRUE = 1;
typedef unsigned int bool;

int getDpi(Display *dpy, int scr, bool xRes)
{
    /*
     * an inch is 25.4 millimeters.
     * dpi = N pixels / (M millimeters / (25.4 millimeters / 1 inch))
     *     = N pixels / (M inch / 25.4)
     *     = N * 25.4 pixels / M inch
     */

    double res = xRes ? ((((double) DisplayWidth(dpy,scr)) * 25.4) / ((double) DisplayWidthMM(dpy,scr)))
        : ((((double) DisplayHeight(dpy,scr)) * 25.4) / ((double) DisplayHeightMM(dpy,scr)));

    return (int) (res + 0.5);
} // print_Screen_info

int main(int argc, char *argv[])
{
    Display *dpy;           /* X connection */
    char *displayname = NULL;       /* set to what you want or need */
    dpy = XOpenDisplay (displayname);
    if (!dpy) 
    {
    fprintf (stderr, "xdpi:  unable to open display \"%s\".\n",
         XDisplayName (displayname));
    exit (1);
    }

    for (int i = 0; i < ScreenCount(dpy); ++i)
        printf ("Xdpi: %d, Ydpi %d\n", 
                getDpi(dpy, i, TRUE),
                getDpi(dpy, i, FALSE));
} // main

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)