Search code examples
javamacrosimagej

Is there a way to call imagej macro (.ijm) from java (i.e. have macro stored as string and execute it using a java control of imagej)?


It is reversed problem to:

How can I call/execute a java program from an ImageJ macro?

Whenever I write imagej I refer to fiji.

Of course a trivial solution is to create a .ijm from java string and call imagej using a system call with .ijm as an argument, but I search for better solution. Alternatively .ijm instructions can be translated into java calls but it is not very convenient (when .jvm is enough for the job it is very convenient way to keep it in this format).

Why is it useful? It can be used e.g. to distribute a .ijm macro in obfuscated way - make it more difficult to the user to extract the macro. String containing instructions for .ijm can be decrypted only when correct password is provided, etc. Thank you for any suggestions!


Solution

  • Use the ij.IJ.runMacro(String) method.

    Here is an example:

    import ij.IJ;
    import ij.plugin.PlugIn;
    
    public class Run_Macro implements PlugIn {
        @Override
        public void run(final String arg) {
            final String macro =
                "run(\"Clown (14K)\");\n" +
                "run(\"Make Binary\");\n";
            IJ.runMacro(macro);
        }
    }
    

    A word of warning about obfuscation, though: Java is notoriously easy to decompile.