Is there a pure IJ2 way to open an Img<T> from a resource in a jar file?

I am trying to learn to do things the IJ2 way. What’s the cleanest
way to open an in-jar resource as an Img<T>?

For example, is it possible to pass something like a
path-to-jar-resource String to ImgOpener.openImgs()?

Or might it be possible to directly wrap or convert a
sun.awt.image.ToolkitImage to an Img<T> without first
converting it to an ImagePlus?

Here is my non-pure-IJ2 way to open a jar image.

My jar:

   jar tf myPlugin.jar

My code (in

  URL url = getClass().getResource ("/resources/myImage.jpg");
  Image myImage = Toolkit.getDefaultToolkit().getImage(url);            
  ImagePlus myImagePlus = new ImagePlus("myImagePlus", myImage);
  Img<T> myImgT = (Img<T>) ImagePlusAdapter.wrap (myImagePlus);

(url is of specific type, and myImage is of type

This works, all is good, but is it possible to replace these calls (or
some of them) by a single IJ2 call (or at least fewer IJ2 calls)?

I’m just looking for the “IJ2-approved” way of doing this.

Thanks, mm.

1 Like

Dear @mountain_man,

I had a quick look at some tests from the imagej-ops project because I knew some of them are using images to compare with. In a test in one of the recently added Ops, I found the following code and comment:

// HACK: Read data from file system for now.
// Until this is fixed, the test will not pass when run from a JAR file.
String source = "src/test/resources/net/imagej/ops/coloc/" + relPath;
try {
	return (Img) opener.openImgs(source).get(0);
catch (final ImgIOException exc) {
	throw new IllegalStateException("File " + relPath +
		" is unexpectedly inaccessible?");

Judging from the comment, I fear that there currently is no “proper” way. Maybe @ctrueden and/or @gab1one could also comment on this.


Hi Stefan -

Thank you again for your response.

Nice detective work.

I will stick with my “old-fashioned” way for now. I will mark this solved,
as you have answered my question.

Thanks, mm.

1 Like

Just stumbled across this topic searching for other information,
and thought I should share the way I proceed to open an image
from a jar using the scijava framework. It’s slightly longer than
the OP’s way, but uses neither Toolkit nor IJ1 classes: first
copy the resource from the jar to a temporary file, then open the
temporary file the usual way. The temporary file is created using
File.createTempFile, and immediately marked deleteOnExit, so we
reduce chances of cluttering the filesystem. Depending on how
temporary files are handled, on some systems the file will not
even be written to any physical disc. See the functions
openSciJava(URI uri), jarURItoTmpFileURI(URI uri) and
jarURItoTmpFile(URI uri) here:

I don’t know how this could be integrated into the IOService
framework (new service ? patch existing service ?), but if
someone cares to describe how it should best be done, I can try
to work out a pull request.