String to image (quick)

Version (5.51 KB) by Serge
Convert text string to RGB image (quickly) by using a dictionary of pre-generated images.
Updated 9 Apr 2022

View License

Two functions str2im and str2imq.
str2im: Convert text string to RGB image.
% str2im %display example text
% str2im(str) %text as char array or cellstr
% str2im(str,pad) %margin: [N] or [H V] or [L R T B] as pixels or nan
% str2im(__,props) %text property as value pairs, doc text
% I = str2im(__) %return RGB image data as uint8
% [I,A] = str2im(__) %return background alpha channel as uint8
% [I,A,H,W] = str2im(__) %return image height and width
%-If a margin is nan then the background is cropped up to the text.
%-Slow because nothing is cached, a figure is generated for each call and
% print is used to generate the image (not getframe).
%-Maximum image size is limited by screen resolution.
clf,I=str2im({'str' '2im'},[10 8 -6 -5],'Color','b','Background','y','FontName','FixedWidth','FontWeight','bold')
Example: burn text into image
[I,A,H,W]=str2im(datestr(now),[0 0 -6 -3],'FontName','FixedWidth','Color','y','Background','k');
str2imq: Quickly convert text to image by making and using an image dictionary.
% str2imq([]) -clear the cache
% str2imq(L,P) -cache text & properties
% D = str2imq() -get dictionary
% I = str2imq(T,P) -convert text to image using cache
% [I,A] = str2im(__) -return alpha (see str2im)
% [I,A,H,W] = str2im(__) -return height & width (see str2im)
%L: List of letters (char) or list string fragments (cellstr).
%P: Text padding & text properties (see str2im).
%D: Image dictionary of letters/string fragments (struct).
%T: Can also pointers at dictionary entries (integer vector).
%-Dictionary images must have same height to concatenate horizontally.
%-Dictionary and text properties are cached as persistent variables.
%-Missing dictionary element will get appended on the fly (SLOW).
%-Text properties must be exactly same: property order, spelling, etc.
[I,A]=str2imq('Hello!','FontSize',80); %fast repeat calls
imagesc(I,'AlphaData',A), axis off equal
Example: string fragments
imagesc(str2imq({'\pi' '\int' 'xyz'},'Interpreter','tex')), axis equal tight
Example: clock
str2imq('0123456789:.',[0 0 0 0],'FontName','FixedWidth') %init
while 1,imagesc(str2imq(datestr(now,'HH:MM:SS.FFF'))),drawnow,end %play

Cite As

Serge (2024). String to image (quick) (, MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2022a
Compatible with any release
Platform Compatibility
Windows macOS Linux
Find more on Convert Image Type in Help Center and MATLAB Answers

Community Treasure Hunt

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

Start Hunting!
Version Published Release Notes



Added str2imq


Fixed pad feature by replacing buggy getframe with a print command. Much slower now...

Minor changes
Minor changes
Fix to keep window on top

Minor changes
Minor changes