## Convert image to a c++ header file

Asked by Thilina Prasanga Doremure Gamage

on 14 Mar 2019

### Saipraveen (view profile)

on 30 Sep 2019
Hi all,
I'm a newbie to Matlab programming. Can you guys please tell me the way of converting an image file to a C++ header file in matlab. I found a script which i suspect might do the job but ca't get it to work.. :/
The script is as below;
%EXPORT_IMG_2_HEADER Summary of this function goes here
% Detailed explanation goes here
sizeArray = numel(img);
fileID = fopen(filename,'w');
fprintf(fileID,'unsigned char img[%d] = {',sizeArray);
img_sq = reshape(img,[1 sizeArray]);
for idx = 1:numel(img_sq)
val = img_sq(idx);
if idx ~= sizeArray
fprintf(fileID,'%d ,',val);
else
fprintf(fileID,'%d',val);
end
end
fprintf(fileID,'};\n');
fclose(fileID);
end

Jan

### Jan (view profile)

on 14 Mar 2019
Please mention, what "can't get it to work" means. The code looks fine, so I guess you made a mistake at calling it.

R2018b

on 14 Mar 2019
Edited by Jan

### Jan (view profile)

on 14 Mar 2019

Maybe this helps - smarter without a loop:
[fileID, msg] = fopen(filename, 'W');
if fileID == -1
error('Cannot open file for writing: %s, %s', filename, msg);
end
% Maybe:
img = im2uint8(img);
n = numel(img);
fprintf(fileID, '// Image on header\nunsigned char img[%d] = {', n);
fprintf(fileID,'%d ,', img(1:n-1));
fprintf(fileID,'%d};\n', img(n));
fclose(fileID);
end

#### 1 Comment

Thilina Prasanga Doremure Gamage

### Thilina Prasanga Doremure Gamage (view profile)

on 14 Mar 2019
Hi Jan,
Thank u so much for the quick response :) I'm really new to this.. first i tried to put the image in a varible called img and run the script after. i have no idea how this script call the image. can u please explain? sorry i know this is stupid but im trying to learn image processing by following a tutorial..

### Saipraveen (view profile)

on 30 Sep 2019

In this file exchange - https://www.mathworks.com/matlabcentral/fileexchange/72535-image-to-c-c-array-converter, I have written a script to generate a C/C++ array which can be saved as a header file for use with various embedded displays.
Hope that helps.