[Tex/LaTex] Check for a valid file before using \includegraphics

external filesgraphics

I know how to check if a given argument represents an existing file (see this question).

But is there also a possibility to check if this file can be included by \includegraphics?

What I want to achieve is a command that

  • includes an image (and does some more things) if it can, but
  • includes some kind of info box and adds an entry to a 'list of missing images' if the argument doesn't point to a (existing and valid) image file.

Best Answer

Second attempt

This here should do the same tests than \includegraphics. That means if will give yes if the graphics/file exists and if the extension can be handled be the engine (so tiger.eps will give different results with pdflatex and latex: (The code is from the definition of \Ginclude@graphics in graphics.sty).

\documentclass[]{article}
\usepackage{graphicx}

\makeatletter
\newif\ifgraphicexist

\catcode`\*=11
\newcommand\imagetest[1]{%
 \begingroup
 \global\graphicexisttrue
   \let\input@path\Ginput@path
  \filename@parse{#1}%
  \ifx\filename@ext\relax
    \@for\Gin@temp:=\Gin@extensions\do{%
      \ifx\Gin@ext\relax
        \Gin@getbase\Gin@temp
      \fi}%
  \else
    \Gin@getbase{\Gin@sepdefault\filename@ext}%
    \ifx\Gin@ext\relax
       \global\graphicexistfalse
       \def\Gin@base{\filename@area\filename@base}%
       \edef\Gin@ext{\Gin@sepdefault\filename@ext}%
    \fi
  \fi
  \ifx\Gin@ext\relax
         \global\graphicexistfalse
    \else 
       \@ifundefined{Gin@rule@\Gin@ext}%
         {\global\graphicexistfalse}%
         {}%
    \fi  
  \ifx\Gin@ext\relax 
   \gdef\imageextension{unknown}%
  \else
   \xdef\imageextension{\Gin@ext}%
  \fi 
 \endgroup 
 \ifgraphicexist
  \expandafter \@firstoftwo
 \else
  \expandafter \@secondoftwo
 \fi 
 } 
\catcode`\*=12
\makeatother 

\begin{document}

\imagetest{tiger}{Yes, \imageextension}{No, \imageextension}

\imagetest{tiger.eps}{Yes, \imageextension}{No, \imageextension}

\imagetest{fail}{Yes, \imageextension}{No, \imageextension}

\imagetest{failxxx.eps}{Yes, \imageextension}{No, \imageextension}

\imagetest{bib.bib}{Yes, \imageextension}{No, \imageextension}
\end{document}