選擇性地使用 PNG 或 PDF 來外部化 TikZ 圖片

選擇性地使用 PNG 或 PDF 來外部化 TikZ 圖片

透過 ImageMagics,可以要求外部化 TikZ 圖片的程式碼將產生的 PDF 轉換為 PNG 圖形。

然而,這為一些輕的人物提供了更高的人物權重。

我想要的是有一個重量檢查代碼來選擇兩者中最輕的數字。這樣,較輕的圖形將保持向量(這是理想的),而較重的圖形將變成 PNG(允許更合理的重量,從而節省空間和顯示時間)。

我在 PDF 外部化函數中使用了從 20ko 到 9MO 的大量數字。它們是從循環中自動生成的,這使得手動選擇成為一個問題。

這是一個 MWE,理想情況下第一個圖形是向量的,第二個 PNG 是自動的(這裡我手動強制它)。

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{external}
\tikzexternalize[mode=list and make]

\tikzset{
    png export/.style={
        % First we call ImageMagick; change settings to requirements
        external/system call/.add={}{; convert -density 100 -transparent white "\image.pdf" "\image.png"},
        % Now we force the PNG figure to be used instead of the PDF
        /pgf/images/external info,
        /pgf/images/include external/.code={
            \includegraphics[width=\pgfexternalwidth,height=\pgfexternalheight]{##1.png}
        },
    }
}

\begin{document}

\begin{tikzpicture}
    \draw (0,0) circle (1) ;
\end{tikzpicture}

% Activate the plot as png
\tikzset{png export}

\begin{tikzpicture}
\foreach \xnum in {1,2,3,...,99,100}
{
    \draw (0,0) circle (1) ;
}
\end{tikzpicture}

\end{document}

基本上,我認為這可能會在 中添加一些程式碼/pgf/images/include external/.code,以查看大小,並通過一些邏輯,決定使用 PNG 或 PDF。

答案1

system call顯然你可以如下擴充:

    external/system call/.add={}{;
        convert -density 100 -transparent white "\image.pdf" "\image.png";
        wc -c "\image.pdf" | awk '{print "PDF is " $1}';
        wc -c "\image.png" | awk '{print "PNG is " $1}';
        echo "what is next? sir?"
    }

這會給你

現在您可以透過 shell 編寫您的邏輯。

答案2

根據與 @Symbol 1 的討論,我得出以下結論:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{external}
\tikzexternalize[mode=list and make]

\tikzset{
    png export/.style={
        % First we call ImageMagick; change settings to requirements
        external/system call/.add={}{; convert -density 100 -transparent white "\image.pdf" "\image.png";
            mkdir -p fig2plot;
            if [[ `wc -c "\image.pdf" | cut -d' ' -f1;` -lt `wc -c "\image.png" | cut -d' ' -f1;` ]];
            then cp "\image.png" fig2plot;
            else cp "\image.pdf" fig2plot;
            fi},
        % Now we force the PNG figure to be used instead of the PDF
        /pgf/images/external info,
        /pgf/images/include external/.code={
            \includegraphics[width=\pgfexternalwidth,height=\pgfexternalheight]{fig2plot/##1}
        },
    }
}

\begin{document}

% Activate the plot as png
\tikzset{png export}

\begin{tikzpicture}
    \draw (0,0) circle (1);
\end{tikzpicture}

\begin{tikzpicture}
\foreach \xnum in {1,2,3,...,99,100}
{
    \draw (0,0) circle (1) ;
}
\end{tikzpicture}

\end{document}

它創建一個子資料夾,在其中複製最小的圖像,然後從該子資料夾中進行繪圖,無論擴展名如何。

然而,雖然 makefile 中的命令可以在 shell 中運行,但if似乎有一個缺陷:

/bin/sh: 1: [[: not found

資料夾中的兩個數字都是 pdf (所以if總是錯誤的,而當我在 bash 中嘗試該命令時,它給出了正確的答案)。

相關內容