1

I would like to add many images to my document. The images are located in a folder named ./assets/images/ and are numbered as follows 0.png, 1.png, ..., 100.png. How can I include them using a for-loop in Latex?

At the moment I do the following, which is not very aesthetic:

\begin{figure}
    \centering
    \includegraphics{./assets/images/1.png}
    \includegraphics{./assets/images/2.png}
    \includegraphics{./assets/images/3.png}
    \includegraphics{./assets/images/4.png}
    % and so on
    \caption{}
    \label{}
\end{figure}

Is there a way to do something like this:

\begin{figure}
    \centering
    for image in images:
        \includegraphics{./assets/images/ + image}
    \caption{}
    \label{}
\end{figure}

2 Answers 2

3

The pgffor package provides a very simple interface for loops like this. I've made a helper command to change the number of images as you need; this is useful if you're using the same technique multiple times in your document, but you could just as easily hardcode the top value.

Assuming your images are named as in your example.

\documentclass{article}
\usepackage{graphicx}
\usepackage{pgffor}
\newcommand{\setnumimages}[1]{\def\numimages{#1}}
\begin{document}
\setnumimages{5}
\begin{figure}
\foreach \x in {1,...,\numimages}{
    \includegraphics{./assets/images/\x}
}
\end{figure}
\end{document}
4
  • 1
    How can I modify your example to load images from a folder with arbirary names?
    – Gilfoyle
    Commented Jun 21, 2020 at 10:27
  • @random9 I'm not quite sure what you mean. You can build filenames out of macros. Can you give an example of what you mean by an "arbitrary" name?
    – Alan Munn
    Commented Jun 21, 2020 at 11:44
  • Sure, let's say instead of 1.png, 2.png, ... I have something like bla.png, foo.png, ...
    – Gilfoyle
    Commented Jun 21, 2020 at 12:29
  • 2
    @random9 Instead of doing \foreach \x in {1,...,\numimages} you can give a literal list: \foreach \x in {fee,fie,fo,fum,foo,bar}.
    – Alan Munn
    Commented Jun 21, 2020 at 13:31
0

my working example :

% mwe.tex 
\documentclass{article}
\usepackage{pgffor}  
\usepackage{mwe}
\usepackage{graphics}
\begin{document}

\foreach \fig in {a,b,c}%
   {My picture: example-image-\fig \par%
   \includegraphics[width=4cm]{example-image-\fig}%
     \par%
     \vspace{2ex}}
\end{document}
2
  • 1
    How is this different from my answer?
    – Alan Munn
    Commented Apr 26, 2020 at 18:54
  • 1
    Not really, but my code is a complete example executable without any adaptation. For a beginner, it can help. I put it in response because we cannot publish any code as a comment.
    – gigiair
    Commented Apr 26, 2020 at 21:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .