How can I make an image file path relative to an mlapp file that uses it?

39 visualizaciones (últimos 30 días)
I want to include an image in an App Designer app, The image file is in the same folder as the .mlapp file, but when I navigate the current MATLAB directory away from that folder and then run the app it doesn't find the image. How can I make the app always find the image no matter the current directory?

Respuesta aceptada

MathWorks Support Team
MathWorks Support Team el 21 de Dic. de 2020
Editada: MathWorks Support Team el 21 de Dic. de 2020
When given a relative file path, MATLAB will search the current directory and then the MATLAB path. When the current directory is a folder containing both the .mlapp file and an image file, 'icon.png', calling "uiimage(app.UIFigure, 'ImageSource', 'icon.png');" finds the image, but if the current MATLAB directory is different from that folder then it won't be found unless it is on the MATLAB path. The absolute file path can be hard coded, but this makes the app difficult to share between users. Commands like "pwd" also return the path to the current MATLAB directory, and not the path to the directory of the script that called it.
 
To obtain the absolute path to the image at run time, the following lines can be added to "startupFcn" in the .mlapp file:
 
imageFile = 'icon.png';
absPath = fileparts(mfilename('fullpath')); % absolute path to the folder containing the mlapp file
imageAbsolute = fullfile(absPath, imageFile); % absolute path to the image file
uiimage(app.UIFigure, 'ImageSource', imageAbsolute);

Más respuestas (0)

Categorías

Más información sobre Convert Image Type en Help Center y File Exchange.

Productos


Versión

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by