# Passing image path to \includegraphics using a macro

I'm trying to use a single environment for a number of different cases. For each case, I need the environment to have a different image associated with it.

When I try this, I get

! LaTeX Error: File image1.png' not found.


An example illustrates what I'm trying to do:

\documentclass{memoir}

\usepackage{graphicx}

\newcommand{\ImageOne}{image1.png}
\newcommand{\ImageTwo}{image2.png}
\newcommand{\currentimage}{}

\newcommand{\MyFigure}{%
\begin{figure}
\centering
\includegraphics[width=0.5\linewidth]{\currentimage}
\end{figure}}

\begin{document}

\renewcommand{\currentimage}{\ImageOne}
\MyFigure

\renewcommand{\currentimage}{\ImageTwo}
\MyFigure

\end{document}


Apparently \includegraphics does only one step of expansion for its argument, so you end up with \includegraphics[width=0.5\linewidth]{\ImageOne} and this is not what TeX expects.

Use \let instead of \renewcommand:

\documentclass{memoir}

\usepackage{graphicx}

\newcommand{\ImageOne}{image1.png}
\newcommand{\ImageTwo}{image2.png}

\newcommand{\MyFigure}{%
\begin{figure}
\centering
\includegraphics[width=0.5\linewidth]{\currentimage}
\end{figure}}

\begin{document}

\let\currentimage\ImageOne
\MyFigure

\let\currentimage\ImageTwo
\MyFigure

\end{document}


However, I don't think this is a good way to go.

It is far more natural in LaTeX to use an argument as in the other answer, however if you want to keep the interface you have then you need to expand the macro before passing it to \includegraphics.

\newcommand{\MyFigure}{%
\begin{figure}
\centering
\edef\tmp{\noexpand\includegraphics[width=0.5\linewidth]{\currentimage}}\tmp
\end{figure}}


Simplified version and it works.

\documentclass{memoir}

\usepackage{graphicx}

\newcommand{\ImageOne}{example-image-a}
\newcommand{\ImageTwo}{example-image-b}
\newcommand{\MyFigure}[1]{%
\begin{figure}
\centering
\includegraphics[width=0.5\linewidth]{#1}
\end{figure}}

\begin{document}

\MyFigure{\ImageOne}

\MyFigure{\ImageTwo}

\end{document}
`
• This is a good way to solve the problem, however, I don't want a different command call for the different use cases. I'm working on a book and each chapter has different styling, which I'd like to change globally on a per chapter basis, if possible. – ezietsman Jun 25 '13 at 9:25