ImageJ macro make new folder and save output in new folder

Nick picture Nick · Mar 22, 2016 · Viewed 11.2k times · Source

I modified the following macro I found on an ImageJ message board to batch split channels, create a new folder called "OneChannel" and save the output in the new folder. The code works as expected: it creates the new folder, it splits the channels, and saves them under a new name. The only problem is that it saves the new files in the same folder as the originals and I have to manually drag them to the newly created folder afterwards. I have tried messing with this but I cannot get it to work. Any input would be appreciated, I am very new to Java.

dir=getDirectory("Choose a Directory"); 
print(dir); 
splitDir= dir + "OneChannel"; 
print(splitDir); 
File.makeDirectory(splitDir); 
list = getFileList(dir); 

for (i=0; i<list.length; i++) { 
     if (endsWith(list[i], ".tif")){ 
               print(i + ": " + dir+list[i]); 
             open(dir+list[i]); 
             imgName=getTitle(); 
         baseNameEnd=indexOf(imgName, ".tif"); 
         baseName=substring(imgName, 0, baseNameEnd);
         run("Split Channels"); 
         selectWindow(imgName + " (blue)"); 
         close(); 
         selectWindow(imgName + " (green)"); 
         saveAs("Tiff",  splitDir + baseName +  "-AnkG.tif"); 
         close(); 
         selectWindow(imgName + " (red)");
         run("Close All"); 
     } else {
     write("One Channel Conversion is Complete");
     }
} 

Answer

Nick picture Nick · Mar 22, 2016

I actually figured this out. In line 3 I needed to put "/OneChannel/". As soon as I did that it is working fine. I guess I was not specifying a real file path before, but the following works fine now.

dir=getDirectory("Choose a Directory"); 
print(dir); 
splitDir= dir + "/OneChannel/"; // This was my error, I left out "//" surrounding OneChannel
print(splitDir); 
File.makeDirectory(splitDir); 
list = getFileList(dir); 

for (i=0; i<list.length; i++) { 
     if (endsWith(list[i], ".tif")){ 
               print(i + ": " + dir+list[i]); 
             open(dir+list[i]); 
             imgName=getTitle(); 
         baseNameEnd=indexOf(imgName, ".tif"); 
         baseName=substring(imgName, 0, baseNameEnd);
         run("Split Channels"); 
         selectWindow(imgName + " (blue)"); 
         close(); 
         selectWindow(imgName + " (green)"); 
         saveAs("Tiff",  splitDir + baseName "-AnkG.tif"); 
         close(); 
         selectWindow(imgName + " (red)");
         run("Close All"); 
     } else {
     write("One Channel Conversion is Complete");
     }
}