[Tex/LaTex] How to get the aspect ratio of an image programmatically

graphicstikz-pgf

How can I get the aspect ratio of an image and store it in a pgf macro for further calculations? For example:

\documentclass{article}

\usepackage{graphicx}
\usepackage{tikz}

\begin{document}

\includegraphics{image.jpg}

\begin{tikzpicture}
\pgfmatsetmacro{\aspectratio}{???} % This variable should contain the aspect ratio of image.jpg
\end{tikzpicture}
\end{document}

Best Answer

Here is an \aspectratio macro that either prints the aspect ratio or stores it in a macro given as optional argument. The *-form will do a global assignment, in case you need it. The macro (in the example it is \test) can be used in \pgfmathsetmacro or other environment accepting floating point numbers.

\documentclass{article}
\usepackage{xparse} % also loads expl3
\usepackage{graphicx}

\ExplSyntaxOn
\NewDocumentCommand{\aspectratio}{smo}
 {% #2 is the image file
  \hbox_set:Nn \l_tmpa_box {\includegraphics{#2}}
  \IfNoValueTF{#3}
   {
    \__student_aspectratio:nn { \box_wd:N \l_tmpa_box } { \box_ht:N \l_tmpa_box }
   }
   {
    \IfBooleanTF{#1}{ \tl_gset:Nx } { \tl_set:Nx } #3
     {
      \__student_aspectratio:nn { \box_wd:N \l_tmpa_box } { \box_ht:N \l_tmpa_box }
     }
   }
 }

\cs_new:Nn \__student_aspectratio:nn
 {
  \fp_eval:n {round( #1 / #2 , 5)}
 }
\ExplSyntaxOff

\begin{document}

\aspectratio{example-image}

\aspectratio{example-image-1x1}

\begingroup
\aspectratio*{example-image-9x16}[\test]
\endgroup

\texttt{\meaning\test}

\end{document}

enter image description here