Undocumented Matlab
  • SERVICES
    • Consulting
    • Development
    • Training
    • Gallery
    • Testimonials
  • PRODUCTS
    • IQML: IQFeed-Matlab connector
    • IB-Matlab: InteractiveBrokers-Matlab connector
    • EODML: EODHistoricalData-Matlab connector
    • Webinars
  • BOOKS
    • Secrets of MATLAB-Java Programming
    • Accelerating MATLAB Performance
    • MATLAB Succinctly
  • ARTICLES
  • ABOUT
    • Policies
  • CONTACT
  • SERVICES
    • Consulting
    • Development
    • Training
    • Gallery
    • Testimonials
  • PRODUCTS
    • IQML: IQFeed-Matlab connector
    • IB-Matlab: InteractiveBrokers-Matlab connector
    • EODML: EODHistoricalData-Matlab connector
    • Webinars
  • BOOKS
    • Secrets of MATLAB-Java Programming
    • Accelerating MATLAB Performance
    • MATLAB Succinctly
  • ARTICLES
  • ABOUT
    • Policies
  • CONTACT

Images in Matlab uicontrols & labels

October 17, 2012 29 Comments

A couple of weeks ago, a reader here asked how to integrate images in Matlab labels. I see quite a few queries about this, so I wanted to take today’s opportunity to explain how this can be done, and how to avoid common pitfalls.
In fact, there are two main methods of displaying images in Matlab GUI – the documented method, and the undocumented one:

The documented method

Some Matlab uicontrols (buttons, radio and checkboxes) have the CData property that can be used to load and display an image. For example:

imgData = imread('myImage.jpg');   % or: imread(URL)
hButton = uicontrol('CData',imgData, ...);

imgData = imread('myImage.jpg'); % or: imread(URL) hButton = uicontrol('CData',imgData, ...);

While label uicontrols (uicontrol(‘style’,’text’, …)) also have the CData property, it has no effect on these controls. Instead, we can create an invisible axes that displays the image using the image function.

The undocumented method

web-based images

I’ve already written extensively about Matlab’s built-in support for HTML in many of its controls. The supported HTML subset includes the <img> tag, and can therefore display images. For example:

htmlStr = '<html><b>Logo</b>: <img src="http://undocumentedmatlab.com/images/logo_68x60.png"/></html>';
hButton = uicontrol('Position',[10,10,120,70], 'String',htmlStr, 'Background','white');

htmlStr = '<html><b>Logo</b>: <img src="http://undocumentedmatlab.com/images/logo_68x60.png"/></html>'; hButton = uicontrol('Position',[10,10,120,70], 'String',htmlStr, 'Background','white');

uicontrol with HTML image
uicontrol with HTML image

local images

Note that the image src (filename) needs to be formatted in a URL-compliant format such as 'http://www.website.com/folder/image.gif' or 'file:/c:/folder/subfolder/img.png'. If we try to use a non-URL-format filename, the image will not be rendered, only a placeholder box:

uicontrol('Position',..., 'String','<html><img src="img.gif"/></html>');  %bad
uicontrol('Style','list', ... 'String',{...,'<html><img src="img.gif"/></html>'});  %bad

uicontrol('Position',..., 'String','<html><img src="img.gif"/></html>'); %bad uicontrol('Style','list', ... 'String',{...,'<html><img src="img.gif"/></html>'}); %bad

Ill-specified HTML images in Matlab uicontrols Ill-specified HTML images in Matlab uicontrols
Ill-specified HTML images in Matlab uicontrols

Instead, we need to use correct URI syntax when specifying local images, which means using the 'file:/' protocol prefix and the '/' folder separator:

>> iconsFolder = fullfile(matlabroot,'/toolbox/matlab/icons/');
>> iconUrl = strrep(['file:/' iconsFolder 'matlabicon.gif'],'\','/');
>> str = ['<html><img src="' iconUrl '"/></html>']
str =
<html><img src="file:/C:/Program Files/MATLAB/ ..... /icons/matlabicon.gif"/></html>
>> uicontrol('Position',..., 'String',str);
>> uicontrol('Style','list', ... str});

>> iconsFolder = fullfile(matlabroot,'/toolbox/matlab/icons/'); >> iconUrl = strrep(['file:/' iconsFolder 'matlabicon.gif'],'\','/'); >> str = ['<html><img src="' iconUrl '"/></html>'] str = <html><img src="file:/C:/Program Files/MATLAB/ ..... /icons/matlabicon.gif"/></html> >> uicontrol('Position',..., 'String',str); >> uicontrol('Style','list', ... str});

Correctly-specified HTML images in Matlab uicontrols Correctly-specified HTML images in Matlab uicontrols
Correctly-specified HTML images in Matlab uicontrols

A similar pitfall exists when trying to integrate images in GUI control tooltips. I already discussed this issue here.
You can use HTML to resize the images, using the <img> tag’s width, height attributes. However, beware that enlarging an image might introduce pixelization effects. I discussed image resizing here – that article was in the context of menu-item icons, but the discussion of image resizing also applies in this case.

images in text labels

As for text labels, since text-style uicontrols do not unfortunately support HTML, we can use the equivalent Java JLabels, as I have explained here. Here too, we need to use the 'file:/' protocol prefix and the '/' folder separator if we want to use local files rather than internet files (http://…).

Java customizations

Using a uicontrol’s underlying Java component, we can customize the displayed image icon even further. For example, we can specify a different icon for selected/unselected/disabled/hovered/pressed/normal button states, as I have explained here. In fact, we can even specify a unique icon that will be used for the mouse cursor when it hovers on the control:

Custom cursor Custom cursor
Custom uicontrol cursors

R2019b and newer

Iin R2019b and later, unless you specify the image size nothing will be shown. A solution is presented in this answer

str = ['<html><img src="file:/' iconUrl '" height="16" width="16"></html>'];

str = ['<html><img src="file:/' iconUrl '" height="16" width="16"></html>'];

Related posts:

  1. Icon images & text in Matlab uicontrols – HTML can be used to add image icons to Matlab listbox and popup (drop-down) controls. ...
  2. Transparency in uicontrols – Matlab uicontrols' CData property can be customized to provide background transparency....
  3. Customizing Matlab labels – Matlab's text uicontrol is not very customizable, and does not support HTML or Tex formatting. This article shows how to display HTML labels in Matlab and some undocumented customizations...
  4. Panel-level uicontrols – Matlab's uipanel contains a hidden handle to the title label, which can be modified into a checkbox or radio-button control...
  5. Uitab colors, icons and images – Matlab's semi-documented tab panels can be customized using some undocumented hacks...
  6. Toolbar button labels – GUI toolbar button labels can easily be set and customized using underlying Java components. ...
GUI HTML Icons image Pure Matlab uicontrol
Print Print
« Previous
Next »
29 Responses
  1. Morteza October 17, 2012 at 12:36 Reply

    Hi Dear Yair
    That was nice point…
    Thanks so much for your help.

  2. Peter Gardman October 20, 2012 at 02:24 Reply

    Dear Yair,
    First, sorry, my petition is not related to this entry, but I didn’t know where to post it.
    I use error(‘…’) when I want to stop execution of a running m-file and show an error message. However, together with the error message, Matlab displays on screen all the other info with the line number or the mfile name where the error occurred (“Error in ==>..”). This distracts from the error message, and the end-user doesn’t care about all this info. I only want to display a message and stop execution. For example:

    if x < 0
       error('x should not be negative')
    end

    if x < 0 error('x should not be negative') end

    with pcoded files the extra info is not shown, but, in a non-compiled mfile, how to make "error(…)" not display all the extra info? Any suggestions are very welcome. Thank you very much.

    • Yair Altman October 20, 2012 at 12:53 Reply

      @Peter – place a try-catch block in the main function of your application:

      function myApp(...)
         try
            ... % main program code
         catch
            disp(lasterr)
         end
      end

      function myApp(...) try ... % main program code catch disp(lasterr) end end

      • Peter Gardman October 21, 2012 at 02:36

        Thank you very much for your answer. Very appreciated.

  3. stetsc March 18, 2013 at 05:27 Reply

    Hi there Yair,

    thanks for this very usefull post. But I have an ongoing question for this topic:

    Is it possible to align text and image vertically centered?

    Because in my Buttons, the text is aligned strictly at the bottom of the image. It would look more “professional” when I could align the text centered to the image.

    • Yair Altman March 18, 2013 at 06:03 Reply

      @Stetsc – yes, we can do this using the underlying Java component:

      jButton = findjobj(hButton);
      jButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);  % or: set(jButton,'HorizontalTextPosition',javax.swing.SwingConstants.CENTER);
      jButton.setVerticalTextPosition(javax.swing.SwingConstants.CENTER);    % or: set(jButton,'VerticalTextPosition',javax.swing.SwingConstants.CENTER);

      jButton = findjobj(hButton); jButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); % or: set(jButton,'HorizontalTextPosition',javax.swing.SwingConstants.CENTER); jButton.setVerticalTextPosition(javax.swing.SwingConstants.CENTER); % or: set(jButton,'VerticalTextPosition',javax.swing.SwingConstants.CENTER);

      This way, we can separately set the text and image locations in many different manners (left/center/right, top/center/bottom). I explain all these options in detail in section 6.1 of my Matlab-Java programming book.

      • stetsc March 18, 2013 at 07:32

        Hi Yair,

        thanks for the quick answer. I tried out, what you told me, but I can’t see any changes in the alignment of the text and image on the Button.

        Here is my code:

        htmlButtonStr_aSi = ['<b>Beschreibung der gewählten Messgröße</b>: '];
        DH.info_aSi = uicontrol(DH.var,'Style','PushButton',...       
                         'Parent',frame_lists,...
                         'Units','normalized', ...
                         'position',v.pos76,...
                         'TooltipString','',...
                         'FontUnits','normalized', ...    
                         'fontsize',0.225,...      
                         'fontweight','normal',...      
                         'String',htmlButtonStr_aSi,...
                         'HorizontalAlignment','left', ...
                         'Enable','on', ...
                         'Callback','msgbox(char(DH.desc((get(DH.aSi,''Value'')))),''Info enthaltene Messgröße'')');
        jButton_info_aSi = findjobj(DH.info_aSi);    %find Java-Handle of Button
        set(jButton_info_aSi,'HorizontalTextPosition',javax.swing.SwingConstants.LEFT);
        set(jButton_info_aSi,'VerticalTextPosition',javax.swing.SwingConstants.CENTER);

        htmlButtonStr_aSi = ['<b>Beschreibung der gewählten Messgröße</b>: ']; DH.info_aSi = uicontrol(DH.var,'Style','PushButton',... 'Parent',frame_lists,... 'Units','normalized', ... 'position',v.pos76,... 'TooltipString','',... 'FontUnits','normalized', ... 'fontsize',0.225,... 'fontweight','normal',... 'String',htmlButtonStr_aSi,... 'HorizontalAlignment','left', ... 'Enable','on', ... 'Callback','msgbox(char(DH.desc((get(DH.aSi,''Value'')))),''Info enthaltene Messgröße'')'); jButton_info_aSi = findjobj(DH.info_aSi); %find Java-Handle of Button set(jButton_info_aSi,'HorizontalTextPosition',javax.swing.SwingConstants.LEFT); set(jButton_info_aSi,'VerticalTextPosition',javax.swing.SwingConstants.CENTER);

        I’m using MATLAB R2009b. Where is my fault?
        Greetings,
        stetsc

      • Yair Altman March 18, 2013 at 07:46
        set(jButton_info_aSi,'HorizontalTextPosition',javax.swing.SwingConstants.LEFT);

        set(jButton_info_aSi,'HorizontalTextPosition',javax.swing.SwingConstants.LEFT);

        not:

        htmlButtonStr_aSi = ['<html><b>Beschreibung der gewählten Messgröße</b>: </html>'];

        htmlButtonStr_aSi = ['<html><b>Beschreibung der gewählten Messgröße</b>: </html>'];

        Also, to use HTML formatting as you are obviously trying to do, you need to add “<html>” to the beginning of your string:

        htmlButtonStr_aSi = ['<html><b>Beschreibung der gewählten Messgröße</b>: </html>'];

        htmlButtonStr_aSi = ['<html><b>Beschreibung der gewählten Messgröße</b>: </html>'];

      • stetsc March 18, 2013 at 08:07

        Oh, I just saw, that your comment-system interprets the HTML-Tags in my first codeline. And with this, you cannot see what I really coded. So I try it this way:

        htmlButtonStr_aSi = ['<html><b>Beschreibung der gewählten Messgröße</b>:<img src="file:' img_path_info '"/>;</html>'];

        htmlButtonStr_aSi = ['<html><b>Beschreibung der gewählten Messgröße</b>:<img src="file:' img_path_info '"/>;</html>'];

        As you can see, I build the string out of the descriptive string “Beschreibung der gewählten Messgröße:” and the variable “img_path_info”.

        So why it does not work?

      • stetsc March 18, 2013 at 08:11

        I have to mention, that the Text and the image appear on the Button, side by side, as I want them to be, but the vertical positions are not really centered. The text is to low and the image to high.

        Thanks for your help.

      • Yair Altman March 18, 2013 at 08:15

        HTML has its own way of aligning the items, just as on a webpage. If you want to have more control then you need to set the image not via HTML but using the uicontrol’s CData property, and then you can control the placement of them separately as I have shown above.

      • stetsc March 18, 2013 at 08:35

        Ah! I understand. Yair, you are my man!

        Now it looks like I want it to. Many thanks for your help.

        Here is the final code for all those who have the same problem out there:

        info_icon_path = fullfile(pwd, 'resourcegraphinfo_icon_transparent.png');
        DH.info_aSi = uicontrol(DH.var,'Style','PushButton',...       
                         'Parent',frame_lists,...
                         'Units','normalized', ...
                         'position',v.pos76,...
                         'TooltipString','',...
                         'FontUnits','normalized', ...    
                         'fontsize',0.45,...      
                         'fontweight','bold',...      
                         'String','Description',...
                         'HorizontalAlignment','left', ...
                         'Enable','on', ...
                         'Callback','msgbox(''It works!'')');
        jButton_info_nFS = findjobj(DH.info_nFS);                                           %find Java-Handle of Button
        set(jButton_info_nFS,'HorizontalTextPosition',javax.swing.SwingConstants.RIGHT);    %align text
        set(jButton_info_nFS,'VerticalTextPosition',javax.swing.SwingConstants.CENTER);     %align text

        info_icon_path = fullfile(pwd, 'resourcegraphinfo_icon_transparent.png'); DH.info_aSi = uicontrol(DH.var,'Style','PushButton',... 'Parent',frame_lists,... 'Units','normalized', ... 'position',v.pos76,... 'TooltipString','',... 'FontUnits','normalized', ... 'fontsize',0.45,... 'fontweight','bold',... 'String','Description',... 'HorizontalAlignment','left', ... 'Enable','on', ... 'Callback','msgbox(''It works!'')'); jButton_info_nFS = findjobj(DH.info_nFS); %find Java-Handle of Button set(jButton_info_nFS,'HorizontalTextPosition',javax.swing.SwingConstants.RIGHT); %align text set(jButton_info_nFS,'VerticalTextPosition',javax.swing.SwingConstants.CENTER); %align text

        And now the button has the image on the left, followed by the descriptive text. Both are vertically centered.

        So again, thanks to you, Yair.

        Greetings,
        stetsc

      • stetsc March 18, 2013 at 08:47

        I forgot one codeline:

        jButton_info_nFS.setIcon(javax.swing.ImageIcon(info_icon_path));    %add image to button

        jButton_info_nFS.setIcon(javax.swing.ImageIcon(info_icon_path)); %add image to button

        Just needs to be added to the previous posted code.
        Sorry 🙂

        stetsc

      • Yair Altman March 18, 2013 at 08:50

        instead of using setIcon you could simply use the CData property:

        imgData = imread(info_icon_path);
        uicontrol(... , 'CData',imgData);

        imgData = imread(info_icon_path); uicontrol(... , 'CData',imgData);

  4. Emanuel R August 2, 2013 at 05:45 Reply

    Hi!
    How can I save the cdata as a gif? I want to use the Icons outside Matlab.
    Thx!

    • Yair Altman August 2, 2013 at 06:19 Reply

      @Emanuel – use the built-in imwrite function

  5. Asaf B July 20, 2015 at 10:28 Reply

    Hi Yair,

    is it possible to display HTML text on axes ?

    %it is not work  
    h_table = axes('HandleVisibility','callback', 'position',[ 0 0  1 1 ]);
    htmlStr = '<b>Logo</b>:';
    h_DataText = text (0.5,0.5 ,htmlStr,'clipping','on','parent',h_table);

    %it is not work h_table = axes('HandleVisibility','callback', 'position',[ 0 0 1 1 ]); htmlStr = '<b>Logo</b>:'; h_DataText = text (0.5,0.5 ,htmlStr,'clipping','on','parent',h_table);

    • Yair Altman July 20, 2015 at 10:53 Reply

      @Asaf – Matlab axes only support tex/latex. For example, to get bold font using Tex,

      text('Position',[0.5, 0.5], 'Interpreter','tex', 'String','bfLogo');

      text('Position',[0.5, 0.5], 'Interpreter','tex', 'String','bfLogo');

      Additional information: http://www.mathworks.com/help/matlab/ref/text-properties.html

    • Asaf B July 21, 2015 at 13:59 Reply

      thank you 🙂

  6. Klaus July 5, 2017 at 11:44 Reply

    Dear Yair,

    thank you for the detailed description. Do you see a chance to put a 90 deg rotated text on a uicontrol (pushbutton)?

    Best regars

    Klaus

    • Yair Altman July 6, 2017 at 15:11 Reply

      @Klaus – not directly, but you can create a small image and add it to the button’s CData. As long as you don’t resize the button too much in either direction, this should work nicely.

  7. Ronit July 16, 2017 at 10:39 Reply

    Do you know a way to show images on push buttons via GUIDE?
    Thanks in advance!

    • Yair Altman July 16, 2017 at 19:27 Reply

      @Ronit – you can update the button’s CData property. Read the Matlab documentation for the uicontrol function for details/examples.

  8. Sneha July 21, 2017 at 09:54 Reply

    Hi Yair
    I added image to my push button using the CData property but was not able to set its position.
    The image added by me is positioned at the center of the button by default. Is there any way to change its position to bottom of the push button

    • Yair Altman July 21, 2017 at 10:14 Reply

      @Sneha – either enlarge your image by adding empty space at the top, or use Java by accessing the button’s underlying Java control and then calling setVerticalAlignment(javax.swing.SwingConstants.BOTTOM).

    • Sneha July 21, 2017 at 14:23 Reply

      Hi Yair,
      Tried enlarging my image and added empty space on top of the image and this worked. Thank you for the help. I wanted to align my text and tried using the following lines

      jButton = findobj(hObject);
      jButton.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
      but got an error stating:
      No appropriate method, property, or field 'setVerticalAlignment' for class 'matlab.ui.control.UIControl'.
       
      Error in MSCT&gt;pushbutton2_CreateFcn (line 812)
      jButton.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
       
      Error in gui_mainfcn (line 95)
              feval(varargin{:});
       
      Error in MSCT (line 44)
          gui_mainfcn(gui_State, varargin{:});
       
      Error in
      matlab.graphics.internal.figfile.FigFile/read&gt;@(hObject,eventdata)MSCT('pushbutton2_CreateFcn',hObject,eventdata,guidata(hObject))

      jButton = findobj(hObject); jButton.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM); but got an error stating: No appropriate method, property, or field 'setVerticalAlignment' for class 'matlab.ui.control.UIControl'. Error in MSCT&gt;pushbutton2_CreateFcn (line 812) jButton.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM); Error in gui_mainfcn (line 95) feval(varargin{:}); Error in MSCT (line 44) gui_mainfcn(gui_State, varargin{:}); Error in matlab.graphics.internal.figfile.FigFile/read&gt;@(hObject,eventdata)MSCT('pushbutton2_CreateFcn',hObject,eventdata,guidata(hObject))

      Can you please help me with this.

      • Yair Altman July 21, 2017 at 14:27

        You need to use findjobj, not findobj. Read the post (and the other articles on this blog) carefully.

    • Sneha July 21, 2017 at 14:30 Reply

      Hi, I am using MATLAB 2016 version

  9. Iliya Romm February 9, 2020 at 12:03 Reply

    To anybody attempting this in R2019b (and later?): unless you specify the image size, nothing will be shown!. A solution is presented in this answer

    str = ['<html><img src="file:/' iconUrl '" height="16" width="16"></html>'];

    str = ['<html><img src="file:/' iconUrl '" height="16" width="16"></html>'];

Leave a Reply
HTML tags such as <b> or <i> are accepted.
Wrap code fragments inside <pre lang="matlab"> tags, like this:
<pre lang="matlab">
a = magic(3);
disp(sum(a))
</pre>
I reserve the right to edit/delete comments (read the site policies).
Not all comments will be answered. You can always email me (altmany at gmail) for private consulting.

Click here to cancel reply.

Useful links
  •  Email Yair Altman
  •  Subscribe to new posts (feed)
  •  Subscribe to new posts (reader)
  •  Subscribe to comments (feed)
 
Accelerating MATLAB Performance book
Recent Posts

Speeding-up builtin Matlab functions – part 3

Improving graphics interactivity

Interesting Matlab puzzle – analysis

Interesting Matlab puzzle

Undocumented plot marker types

Matlab toolstrip – part 9 (popup figures)

Matlab toolstrip – part 8 (galleries)

Matlab toolstrip – part 7 (selection controls)

Matlab toolstrip – part 6 (complex controls)

Matlab toolstrip – part 5 (icons)

Matlab toolstrip – part 4 (control customization)

Reverting axes controls in figure toolbar

Matlab toolstrip – part 3 (basic customization)

Matlab toolstrip – part 2 (ToolGroup App)

Matlab toolstrip – part 1

Categories
  • Desktop (45)
  • Figure window (59)
  • Guest bloggers (65)
  • GUI (165)
  • Handle graphics (84)
  • Hidden property (42)
  • Icons (15)
  • Java (174)
  • Listeners (22)
  • Memory (16)
  • Mex (13)
  • Presumed future risk (394)
    • High risk of breaking in future versions (100)
    • Low risk of breaking in future versions (160)
    • Medium risk of breaking in future versions (136)
  • Public presentation (6)
  • Semi-documented feature (10)
  • Semi-documented function (35)
  • Stock Matlab function (140)
  • Toolbox (10)
  • UI controls (52)
  • Uncategorized (13)
  • Undocumented feature (217)
  • Undocumented function (37)
Tags
AppDesigner (9) Callbacks (31) Compiler (10) Desktop (38) Donn Shull (10) Editor (8) Figure (19) FindJObj (27) GUI (141) GUIDE (8) Handle graphics (78) HG2 (34) Hidden property (51) HTML (26) Icons (9) Internal component (39) Java (178) JavaFrame (20) JIDE (19) JMI (8) Listener (17) Malcolm Lidierth (8) MCOS (11) Memory (13) Menubar (9) Mex (14) Optical illusion (11) Performance (78) Profiler (9) Pure Matlab (187) schema (7) schema.class (8) schema.prop (18) Semi-documented feature (6) Semi-documented function (33) Toolbar (14) Toolstrip (13) uicontrol (37) uifigure (8) UIInspect (12) uitable (6) uitools (20) Undocumented feature (187) Undocumented function (37) Undocumented property (20)
Recent Comments
Contact us
Captcha image for Custom Contact Forms plugin. You must type the numbers shown in the image
Undocumented Matlab © 2009 - Yair Altman
This website and Octahedron Ltd. are not affiliated with The MathWorks Inc.; MATLAB® is a registered trademark of The MathWorks Inc.
Scroll to top