Write an image with file name specified in a variable var1 (char)

6 views (last 30 days)
I need to write an image and I want to give it a name that is stored in a variable var1, which is a 4 byte char. I am trying to use the command imwrite, but it seems not to have this option.

Answers (2)

Image Analyst
Image Analyst on 17 Mar 2016
Try this:
imwrite(yourImageMatrix, var1);
It would be good to add an extension so that it knows the format to write it out in. If var1 does not contain the extension, like 1.jpg, then append an extension and prepend the folder where you want to store the image:
var1 = '1234'; % Whatever - some filename with or without extension.
[~, baseFileName, ext] = fileparts(var1);
if isempty(ext)
ext = '.PNG'; % Make it a PNG format image.
end
fullFileName = fullfile(yourFolder, [baseFileName, ext]);
imwrite(yourImageMatrix, fullFileName);

Walter Roberson
Walter Roberson on 17 Mar 2016
imwrite(TheArray, var1, 'PNG') %example
With your var1 only being 4 bytes, you do not have room for both the base file name and a period and 3 characters of extension, so imwrite is not going to be able to deduce what kind of image you want to create, so you will need to tell it the format.
Note that most other programs will be counting on the extension being there to tell them what kind of image it is, so this may be of limited value.
You should be considering adding on the extension to the file name. For example,
imwrite(TheArray, [var1 '.png'])
  1 Comment
OldCar
OldCar on 17 Mar 2016
I have not explained the problem correctly. The name is a char of 4 letters. I have no limit in var1 size. If it works I could define var1='abcd.png'

Sign in to comment.

Categories

Find more on Convert Image Type in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!