Check if image corrupt before opening via ImageJ macro


I have an imageJ macro script opening many files in batch mode using bioformats.
Unfortunately, I have some files, that fail to open (have not found the reason why).
When this happens, the script breaks and has to be restarted manually.
How can I catch image opening errors without breaking the script?

I have tried the following:

run("Bio-Formats Macro Extensions");
image = pathToImage;
Ext.getFormat(image, format); // comment:returns format e.g.TIF even for broken images
Ext.isThisType(image, thisType); // comment:returns TRUE even for broken images
IJ.redirectErrorMessages(); // comment: error message still shows up
Ext.openImagePlus(image); // comment: works for good.tif, not for corrupt.tif

Please find 2 examples here: (12.2 MB)

Thankful for any ideas!
Best regards,

1 Like

@marioK You could try using the IJ.redirectErrorMessages function to prevent the macro from aborting.

If that does not work, I recommend switching to one of the full-featured script languages, since the ImageJ macro language does not support try/catch style error handling.

See also this 2014 thread from the ImageJ mailing list:


Thank you @ctrueden! I saw the 2014 thread.
Somehow the IJ.redirectErrorMessages function doesn’t work for me.

I’ll look into Jython and Renjin…any preference?

Best regards,

We haven’t tested the Renjin support in a long time, and I don’t think many people use it. But you are certainly welcome to give it a try and report back any problems.

Many people in the community here use Jython regularly, so I know it works reasonably well. It is a great choice, although unfortunately it is still Python 2 syntax, not Python 3.

My personal favorite is Groovy because it works extremely well and is very similar to Java syntactically.

1 Like

Perfect! Groovy looks indeed great! Would help with Qupath scripting as well.
Unfortunately, this would mean learning it from scratch…well…never stop improving…I guess :wink:



Groovy really is very Java-like. The only divergences from Java syntax that I regularly encounter are:

  1. The foreach loop is for (foo in bar) instead of for (foo : bar). Fortunately, if you get this one wrong, Groovy’s error message even tells you to use in instead of :.

  2. The Java-8-functional style for lambda expressions via map and filter uses curly braces instead of parenthesis—e.g.:{item -> item.getNiftyProperty()}.collect() instead of -> item.getNiftyProperty()).collect(Collectors.toList()).

Sure, Groovy supports a bunch of more novel syntax, but you can just write Java style if you want to avoid diverging too much. :smile:

1 Like

FWIW, Groovy 3.0 (release notes) also supports the Java-style Lambda syntax, in addition to the Groovy variant of curly braces for closures.