MATLAB: Open a series of images and save them in another folder

Image Processing Toolboximage save

Hi,I want to open images from one folder and save the 8-bit images in another existed folder using original name. Here is my code:
close all; rand('seed',0);
folder = 'F:' files = [folder filesep '\*.tif']
files = dir(files); n = numel(files)
for k=1:n
fullFileName = fullfile(folder, files(k).name);
idx=randi(k);
im = files(idx).name;
afm = imread(fullfile(folder,im));
I8bit =im2uint8(afm);
[pathstr,name,ext] = fileparts(fullFileName) ; filename = strcat(pathstr,name,'.tif');
my_file = "F:\8bit\filename";
imwrite(I8bit,filename)
end
But the images were not able to be saved in that folder, can anyone help me? Another question is my code can only open jpg files if I change hat to '*\.jpg', with tif (as shown above) not able to open. Can anyone give me a hand? Thank you so much in advance.

Best Answer

You need to have two folder variables, one for input, and one for output. And you need two base file names, one for input and one for output. Then use full file to create two filenames:
fullInputFileName = fullfile(inputFolder, baseInputFileName);
fullOutputFileName = fullfile(outputFolder, baseOutputFileName);
baseInputFileName would be files(k).name.
See full demo below:
% Copies all the files from one folder to another folder.
clc; % Clear the command window.
workspace; % Make sure the workspace panel is showing.
format compact;
% Define input and output folders.
% CHANGE THESE FOLDER NAMES!!!!!!
inputFolder = pwd;
outputFolder = uigetdir(pwd);
if strcmp(outputFolder, inputFolder)
errorMessage = sprintf('Error: the output folder must be different than the input folder');
uiwait(warndlg(errorMessage));
return;
end
% Check to see that both folders exist.
if ~isdir(inputFolder)
errorMessage = sprintf('Error: The following input folder does not exist:\n%s', inputFolder);
uiwait(warndlg(errorMessage));
return;
end
if ~isdir(outputFolder)
errorMessage = sprintf('Error: The following output folder does not exist:\n%s', outputFolder);
uiwait(warndlg(errorMessage));
return;
end
% Get a list of files to copy.
filePattern = fullfile(inputFolder, '*.*'); % All files.
% filePattern = fullfile(inputFolder, '*.m'); % m-files.
fileNamesToTransfer = dir(filePattern);
numFiles = length(fileNamesToTransfer);
% Do the copying.
for k = 1 : numFiles
% Get the base file name.
baseFileName = fileNamesToTransfer(k).name;
% Create the full input and output filenames.
fullInputFileName = fullfile(inputFolder, baseFileName);
fullOutputFileName = fullfile(outputFolder, baseFileName);
fprintf(1, 'Now copying file #%d of %d: %s to %s\n', ...
k, numFiles, fullInputFileName, fullOutputFileName);
copyfile(fullInputFileName, fullOutputFileName);
end
msgbox('Done copy files!', 'modal');