%% Write Images with Custom Write Function
% Create and use a custom writing function to write data in additional formats that are not directly supported by write, such as image files.
%
% Create an image datastore that references all of the sample images in the toolbox/matlab/demos folder. The selected images have the extensions .jpg, .tif, and .png. Convert the datastore to a tall cell array.

demoFolder = fullfile(matlabroot,'toolbox','matlab','demos');
ds = imageDatastore(demoFolder,'FileExtensions',{'.jpg' '.tif' '.png'});
T = tall(ds);

%
% Bring one of the images into memory and display it.

I = gather(T(1));
imshow(I{1},'InitialMagnification',30)

%
% write does not support image files directly, so to write the images out in a different format, you must create a new function to handle the file writing. The writing function receives two inputs from write:
% info is a structure containing fields with information about the current block of data. You can use these fields to construct your own unique file name, or simply use the SuggestedFilename field to use a name suggested by write.
% data is the current block of data, obtained by using read on the datastore.
% The function imageWriter uses the filename suggested by write, and uses imwrite to write the image files to disk as .jpg files. Save this function in your current working folder.

type imageWriter

%
% Write the images in the datastore to a new folder named exampleImages on the C:\ disk. (You can use a different location, especially if you are not using a Windows® computer.) Pass imageWriter as the custom write function using the 'WriteFcn' name-value pair argument.

location = 'C:\exampleImages\image_*.jpg';
write(location, T, 'WriteFcn', @imageWriter)

%
% Display the contents of the folder where the files were written.

dir C:\exampleImages

%
% To read the images back into MATLAB®, create a datastore that references the same location.

ds = imageDatastore(location);
T = tall(ds)

%
% Copyright 2018 The MathWorks, Inc.