 \documentclass{article}
 
\newlength{\myfigurewidth}
\newsavebox{\myfigure}

\newcommand{\myinputfigurewidth}[1]
{
{#1}%قرار دادن شکل
\savebox{\myfigure}{#1}
 \settowidth{\myfigurewidth}{\usebox{\myfigure}}
% \captionsetup{width=\the\myfigurewidth}
}
            
            
\usepackage{caption}
\captionsetup{width=\the\myfigurewidth}

\begin{document}

\begin{figure}[!ht]
\centering
\myinputfigurewidth{
\rule{60mm}{40mm}
}
\caption{caption text caption text caption text caption text 
caption text caption text caption text caption text caption text }
\end{figure}

\end{document}

     