我有一个包含includegraphics命令的命令 - 我可以将图像传递给我的命令,它会在实际包含图像之前为我做一些标准格式化。我通过此命令包含的一些图像小于\ textwidth,而有些则更大。我想将较大的图像缩小到\ textwidth,而不是缩小较小的图像 - 这意味着我不能只做

\includegraphics[width=\textwidth]{img}

有没有办法指定最大宽度?或者,我可以以某种方式获得图像的宽度,以便我可以执行类似

的操作
\ifthenelse{\imagewidth > \textwidth}{%
    \includegraphics[width=\textwidth]{img}}{%
    \includegraphics{img}}
有帮助吗?

解决方案

要获得图像的宽度,您可以使用以下代码:

\newlength{\imgwidth}
\settowidth{\imgwidth}{\includegraphics{img}}

您可以在文档前言中使用它来创建一个自动设置宽度的新命令:

\usepackage{graphicx}
\usepackage{calc}

\newlength{\imgwidth}

\newcommand\scalegraphics[1]{%   
    \settowidth{\imgwidth}{\includegraphics{#1}}%
    \setlength{\imgwidth}{\minof{\imgwidth}{\textwidth}}%
    \includegraphics[width=\imgwidth]{#1}%
}

然后,在您的文档中:

\scalegraphics{img}

我希望这有帮助!

其他提示

我喜欢另外一个参数,可选择向下或向上缩放图像,所以我的\ scalegraphics版本如下所示:

\newcommand\scalegraphics[2][]{%
    \settowidth{\imgwidth}{\includegraphics{#2}}%
    \setlength{\imgwidth}{\minof{#1\imgwidth}{\textwidth}}%
    \includegraphics[width=\imgwidth]{#2}%
}

adjustbox 包对此有用。下面你会看到一个简短的例子。它允许以下(除了修剪,剪裁,添加边距和相对缩放:

\documentclass[a4paper]{article}


\usepackage[demo]{graphicx}
\usepackage[export]{adjustbox}

\begin{document}

\adjustbox{max width=\linewidth}{\includegraphics[width=.5\linewidth,height=3cm]{}}

\adjustbox{max width=\linewidth}{\includegraphics[width=2\linewidth,height=3cm]{}}

\includegraphics[width=2\linewidth,height=3cm,max width=\linewidth]{}
\end{document}

如果使用 export 包选项,则其大多数键可以直接与 \ includegraphics 一起使用。 FOr实例是与您相关的密钥, max width

如果您想要约束的不是图像而是独立的 .tex 文件,您可以稍微修改ChrisN的 \ scalegraphics

\newlength{\inputwidth}
\newcommand\maxwidthinput[2][\linewidth]{%   
    \settowidth{\inputwidth}{#2}%
    \setlength{\inputwidth}{\minof{\inputwidth}{#1}}%
    \resizebox{\inputwidth}{!}{#2}
}

然后像这样使用它

\maxwidthinput{\input{standalone}}
\maxwidthinput[0.5\textwidth]{\input{standalone}}

当然,ted建议的 adjustbox 也可以使用:

\usepackage{adjustbox}
...
\adjustbox{max width=\linewidth}{\input{standalone}}

在搜索CTAN手册和Google搜索结果几分钟后,我想我可以肯定地说,您想要做的事情要么是不可能的,要么是非常困难。我唯一的建议是你有两个命令,一个用于小图像,一个用于大图,或一个带有选项的命令。

可能有办法,但我把它留给其他S.O. LaTeX向导提供了更好的答案。

编辑:我错了,见上文。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top